2016-03-22 51 views
0

我想動態創建一些動作,如下所示。從集合中創建動作

但由於代碼是不是在一個方法,我得到了以下錯誤:「未定義的局部變量或方法」

這是在所有可能的,如果是的話 - 如何?

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

我會質疑你需要單獨的方法爲每個類別,如果所有你做的是呈現索引視圖。如果它比這更復雜,那麼它可能是需要的。 – DickieBoy

回答

2

您可以使用Ruby的define_method

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