Ruby on rails 3 在循环中设置ActiveRecord作用域
为什么这样不行Ruby on rails 3 在循环中设置ActiveRecord作用域,ruby-on-rails-3,activerecord,scopes,Ruby On Rails 3,Activerecord,Scopes,为什么这样不行 class Foo ... Status.each do |status| scope status, where(status: status) end ... end 现在,Foo.new返回的不是Foo的实例,而是ActiveRecord::Relation。在ruby 1.9中尝试一下 Status.each do |status| scope status, -> { where(status: status) } end 或者在以
class Foo
...
Status.each do |status|
scope status, where(status: status)
end
...
end
现在,Foo.new返回的不是Foo的实例,而是ActiveRecord::Relation。在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并不重要。哈哈,太棒了。很高兴我能帮忙!: