【问题标题】:Set ActiveRecord Scopes In A Loop在循环中设置 ActiveRecord 范围
【发布时间】:2013-06-22 08:56:03
【问题描述】:

为什么这不起作用?

class Foo
  ...
  Status.each do |status|
    scope status, where(status: status)
  end
  ...
end

现在Foo.new 它返回的不是 Foo 的实例,而是 ActiveRecord::Relation。

【问题讨论】:

    标签: ruby-on-rails-3 activerecord scopes


    【解决方案1】:

    在 ruby​​ 1.9 中试试这个

    Status.each do |status|
      scope status, -> { where(status: status) }
    end
    

    或在以前的 ruby​​ 版本中

    Status.each do |status|
      scope status, lambda { where(status: status) }
    end
    

    -- 编辑--

    我猜你的问题出在其他地方,因为这段代码对我有用:

    class Agency < ActiveRecord::Base
      attr_accessible :logo, :name
      validate :name, presence: true, uniqueness: true
    
      NAMES = %w(john matt david)
      NAMES.each do |name|
        scope name, -> { where(name: name) }
      end
    end
    

    我可以很好地创建新模型并使用范围

    irb(main):003:0> Agency.new
    => #<Agency id: nil, name: nil, logo: nil, created_at: nil, updated_at: nil>
    irb(main):004:0> Agency.matt
      Agency Load (0.5ms)  SELECT "agencies".* FROM "agencies" WHERE "agencies"."name" = 'matt'
    => []
    irb(main):005:0> Agency.john
      Agency Load (0.3ms)  SELECT "agencies".* FROM "agencies" WHERE "agencies"."name" = 'john'
    => []
    irb(main):006:0> Agency.david
      Agency Load (0.3ms)  SELECT "agencies".* FROM "agencies" WHERE "agencies"."name" = 'david'
    => []
    

    【讨论】:

    • 我试过了。结果相同。顺便说一句,我应该提到我正在使用 Ruby 2.0。
    • 感谢您花时间尝试复制并迫使我深入研究。巨大的呃。 其中一个状态是“新”。 是的。顺便说一句,是否使用 lambda 无关紧要。
    • 哈哈,太棒了。很高兴我能帮助你! :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 2020-03-12
    • 2019-12-28
    • 2017-06-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多