Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I build up an ActiveRecord query incrementally, line by line?

I'd like to piece together an ActiveRecord query using runtime data. What I have in mind is something like...

r = Person.where('last_name LIKE ?', foo)
r.where('created_at < ?', Time.now - 100.days)
r.where( ...some other conditions... )

That doesn't work as intended though. To get it to work you have to chain them together all on one line...

Person.where('last_name LIKE ?', foo) \
  .where('created_at < ?', Time.now - 100.days) \
  .where( ...some other conditions... )

I'm trying to figure out a way to spread it over separate operations on multiple lines.

like image 203
Ethan Avatar asked Apr 13 '12 23:04

Ethan


1 Answers

Query Interface methods (like .where) return a new object. So you just have to hold on to it. See:

r = Person.where('last_name LIKE ?', foo)
r = r.where('created_at < ?', Time.now - 100.days)
r = r.where( ...some other conditions... )
like image 147
Sergio Tulentsev Avatar answered Oct 02 '22 17:10

Sergio Tulentsev