【问题标题】:What am I doing wrong with this define_method?这个define_method我做错了什么?
【发布时间】:2012-10-02 02:49:37
【问题描述】:

好的,所以我想为所有类型设置一个 named_scope,如下所示

class Variety < ActiveRecord::Base
  TYPES = ["holiday", "party", "other", yet_another]

  Variety::TYPES.each do |role|
    define_method
      scope "#{role.to_sym}_applications", where(:type => role)
    end
  end
end

基本上我希望以编程方式定义元的命名范围,以便我可以做到这一点

Variety.holiday_applications
Variety.party_applications
Variety.other_applications
Variety.yet_another_applications

知道我在定义方法上做错了什么

【问题讨论】:

  • 你不需要define_method。
  • 我注意到...发布我的解决方案

标签: ruby-on-rails ruby ruby-on-rails-3 metaprogramming


【解决方案1】:

尝试将您的 to_sym 移动到整个方法名称。

scope "#{role}_applications".to_sym, where(:type => role)

【讨论】:

    【解决方案2】:
     Variety::TYPES.each do |role|
       scope "#{role}_applications".to_sym, where(:type => role)
     end
    

    【讨论】:

    • 解决了...只用了 6 分钟 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-26
    • 2015-02-25
    • 2022-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多