How can I build up an ActiveRecord query incrementally, line by line?
activerecord, arel, ruby, ruby-on-rails, ruby-on-rails-3
Solution
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... )
Problem
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.