0

为什么这不起作用?

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

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

4

1 回答 1

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'
=> []
于 2013-06-25T14:13:05.997 回答