繁体   English   中英

值不为零时,如何在Rails ActiveRecord中应用where子句?

[英]How to apply where clause in Rails ActiveRecord when the value is not nil?

假设我有一个User模型,并且只想在值不为nil时应用一些where子句,否则就丢弃该子句。 有没有比仅使用以下条件更好的方法:

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

还有更多干方法吗?

我通常使用以下方式:

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

User.where(search)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM