Search code examples
ruby-on-railsactioncontrollerruby-on-rails-5

Create actions off of collection


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

Solution

  • 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