从集合中创建动作

Create actions off of collection

我想动态创建一些动作,如下所示。

但由于代码不在方法中,我收到以下错误:"undefined local variable or method"

这是否可能,如果可能 - 如何实现?

class Post < ActiveRecord::Base
  CATEGORIES = [:music,:movies,:art,:jokes,:friends,:whatever].freeze
end

class PostsController < ApplicationController
  Post::CATEGORIES.each do |category|
    eval <<-INDEX_LIKE_ACTIONS
      def #{category}
        @posts = Post.where( category: '#{category}' )
        render :index
      end
    INDEX_LIKE_ACTIONS
  end
end

resources :posts do
   collection do
     Post::CATEGORIES.each {|category| get category.to_s}
   end
end

您可以使用 ruby 的 define_method

Post::CATEGORIES.each do |category|
  define_method category do
    @posts = Post.where(category: category.to_s)
    render :index
  end
end