为什么这不起作用?
class Foo
...
Status.each do |status|
scope status, where(status: status)
end
...
end
现在Foo.new
它不返回Foo的实例,而是返回ActiveRecord :: Relation。
答案 0 :(得分: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'
=> []