【问题标题】:Create actions off of collection从集合中创建操作
【发布时间】:2016-03-22 10:28:02
【问题描述】:

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

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

这有可能吗?如果可以,怎么做?

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-on-rails actioncontroller ruby-on-rails-5


【解决方案1】:

你可以使用ruby的define_method

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-03
    • 2018-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-11
    • 1970-01-01
    相关资源
    最近更新 更多