[英]Rails - how to make query parameters optional in Model?
我正在嘗試使用多個參數在索引上建立一個篩選區域。 我的問題是,如果需要,我不知道如何將它們中的每一個選為可選。 我的意思是,即使我沒有為字段設置值,我也希望過濾器只能與填充的字段一起使用。
我編寫了這段代碼,除了刪除一個或幾個參數外,它都運行良好。
def self.filter(type, min, max, start_at, end_at)
where(type => min..max, :first_date => start_at..end_at).order("#{type}": :desc)
end
我知道我可以使用scope
但是由於我是Rails的新手,所以還不清楚。 如果有人可以提供一些提示? 謝謝!
您可以atrriubte這些到nil
def self.filter(type =nil, min=nil, max=nil, start_at=nil, end_at=nil)
a = YourModel
a = a.where(type => min..max) if min.present? && max.present?
a = a.where(first_date: start_at..end_at) if start_at? && end_at.present?
a = a.order("#{type}#": :desc) if type.present?
a
end
您可以在多個位置鏈接多個
result = where(type => min..max)
result = result.where(first_date: start_at..end_at) if start_date && end_date
return result
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.