Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?
like image 862
psulightning Avatar asked Oct 11 '25 23:10

psulightning


1 Answers

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

scope :active, -> { where(:active=>true) }
like image 89
infused Avatar answered Oct 14 '25 15:10

infused