psulightning
psulightning

Reputation: 176

ActiveRecord Relation with scope

Using Rails 3.2/Ruby 1.9, for example I have the following classes:

class Foo
  has_many :bars
end

class Bar
  scope :active, where(:active=>true)
  # also tried
  # scope :active, lambda{where(:active=>true)}
  # scope :active, -> {where(:active=>true)}
end

Now if I have an instance of Foo (f), and I do f.bars, I get an instance of ActiveRecord::Relation as expected. For some reason though when I do f.bars.active, I get undefined method active for the relation object (I'll buy this as the scope is on the Bar class). I can do f.bars.where(:active=>true) no problem though. I guess my questions are:

  1. What is happening under the hood here?
  2. How can I use the active scope to achieve the desired result?

Upvotes: 4

Views: 1607

Answers (1)

infused
infused

Reputation: 24337

You must wrap the scope statements in a lambda before it will work correctly:

scope :active, -> { where(:active=>true) }

Upvotes: 3

Related Questions