I want to create some actions dynamically, something like the below.
But as the code is not in a method I get the following error: "undefined local variable or method"
Is this at all possible, and if so - how?
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
You can use ruby's define_method
Post::CATEGORIES.each do |category|
define_method category do
@posts = Post.where(category: category.to_s)
render :index
end
end