如果我需要有条件地查询,我尝试这样的方法:
query = Model.find_something
query = query.where(condition1: true) if condition1 == true
query = query.where(condition2: true) if condition2 == true
query = query.where(condition3: true) if condition3 == true
效果很好。 但是我认为这是重复相同代码的一种方式,外观不好。
是否可以不对每个条件表达式的查询重新分配给变量?像这样:
query.where!(condition1: true) # But it can not be in rails :)
我最近开始使用Rails5。
做Rails5的最好方法是什么?
答案 0 :(得分:5)
您可以使用模型范围:
class Article < ApplicationRecord
scope :by_title, ->(title) { where(title: title) if title }
scope :by_author, ->(name) { where(author_name: name) if name }
end
只需链式作用域就可以在任何需要的地方:
Article.by_title(params[:title]).by_author(params[:author_name])
如果参数存在,您将获得有范围的文章,如果没有此类参数,则将获得所有文章