在循环中设置ActiveRecord范围

时间:2013-06-25 14:02:08

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

为什么这不起作用?

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

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

1 个答案:

答案 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'
=> []