从集合中创建操作

时间:2016-03-22 10:28:02

标签: ruby-on-rails actioncontroller ruby-on-rails-5

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

但由于代码不在方法中,我收到以下错误:“未定义的局部变量或方法”

这是否可能,如果是这样 - 怎么样?

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

1 个答案:

答案 0 :(得分:2)

您可以使用ruby的define_method

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