Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mixing ActiveRecord find Conditions

I want to find records on a combination of created_on >= some date AND name IN some list of names.

For ">=" I'd have to use sql condition. For "IN" I'd have to use a hash of conditions where the key is :name and the value is the array of names.

Is there a way to combine the two?

like image 764
Tony Pitale Avatar asked Sep 17 '08 14:09

Tony Pitale


1 Answers

You can use named scopes in rails 2.1 and above

Class Test < ActiveRecord::Base
  named_scope :created_after_2005, :conditions => "created_on > 2005-01-01"
  named_scope :named_fred, :conditions => { :name => "fred"}
end

then you can do

Test.created_after_2005.named_fred

Or you can give named_scope a lambda allowing you to pass in arguments

Class Test < ActiveRecord::Base
  named_scope :created_after, lambda { |date| {:conditions => ["created_on > ?", date]} }
  named_scope :named, lambda { |name| {:conditions => {:name => name}} }
end

then you can do

Test.created_after(Time.now-1.year).named("fred")
like image 141
Laurie Young Avatar answered Sep 29 '22 10:09

Laurie Young