如何逐行逐步建立ActiveRecord查询?

Eth*_*han 6 ruby activerecord ruby-on-rails arel ruby-on-rails-3

我想使用运行时数据拼凑一个ActiveRecord查询.我的想法是......

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

但这并不像预期的那样有效.为了让它工作,你必须将它们连接在一起...

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

我正在试图找到一种方法将它传播到多行的单独操作上.

Ser*_*sev 18

查询接口方法(如.where)返回一个新对象.所以你必须坚持下去.看到:

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