How can I create an ActiveRecord query stepwise, line by line?

I would like to combine an ActiveRecord query using runtime data. What I mean is something like ...

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

This does not work properly. To make it work, you need to link them together on the same line ...

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

I am trying to figure out a way to distribute it in separate operations on several lines.

+5
source share
2 answers

Request methods (e.g. .where) return a new object. So you just need to hold on to it. Cm:

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

, , . Arel, . :

r = Person.where(...
r = r.where('created_at...')

.. ..

+2

All Articles