0

Why doesn't this work?

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

Now Foo.new it returns not an instance of Foo but an ActiveRecord::Relation.

Tim Scott
  • 15,106
  • 9
  • 65
  • 79

1 Answers1

1

Try this in ruby 1.9

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

or in previous ruby versions

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

-- EDIT --

I guess your problem is somewhere else, since this code is working for me:

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

I can create new models just fine and use the scopes

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'
=> []
Ju Liu
  • 3,939
  • 13
  • 18
  • I tried that. Same result. BTW, I should mention I'm on Ruby 2.0. – Tim Scott Jun 25 '13 at 14:27
  • Thanks for taking the time to try to replicate and force me to look deeper. Huge duh. **One of the statuses is 'new'.** Yeah. BTW, using a lambda or not does not matter. – Tim Scott Jun 25 '13 at 18:53