当值不是nil时,如何在Rails ActiveRecord中应用where子句?

时间:2015-11-02 14:05:22

标签: ruby-on-rails activerecord

我们说我有User模型,我想只在值不是nil时应用一些where子句,否则只丢弃该子句。有没有比仅仅使用条件更好的方法:

if ids.nil?
  User.where(active: true)
else 
  User.where(active: true, id: ids)
end

还有更多的干嘛方法吗?

1 个答案:

答案 0 :(得分:1)

我通常会沿着这些方向使用:

search = { active: true }
search[:id] = ids if ids

User.where(search)