[英]Rails - Get contents but only when url param is there
這是一個新問題。 我有一個具有content_type
屬性的Contents
模型。 我有幾個要過濾的content_types,通過URL傳遞類型,例如:/ contents?content_type = blog
我了解我可以根據該參數獲取內容,如下所示:
@contents = Content.where({:content_type => params[:content_type]})
但是當URL參數不存在時,它不會得到任何內容。 我希望當不傳遞URL參數時,將檢索所有內容(無論類型如何)。 我怎么做?
我將定義一個范圍,像這樣(在您的模型內部)
class Content
scope :by_content_type, lambda { |contenttype|
where({:content_type => contenttype}) unless contenttype.blank?
}
end
然后在控制器中使用它,如下所示:
@contents = Content.by_content_type(params[:content_type])
這應該工作:
if params[:content_type].blank? @contents = Content.scoped else @contents = Content.where({:content_type => params[:content_type]}) end
這里有一個合理的模式,它使用一系列鏈接范圍來縮小基於查詢參數的篩選器:
@contents = Content.scoped # Start with no filter
# Optionally narrow filter if filter param is present
type = params[:content_type]
@contents = @contents.where(:content_type => type) if type
@contents = Content.where({(:content_type => params[:content_type]} unless params[:content_type].blank?))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.