我正在尝试在Rails应用程序(仍然是菜鸟)中构建搜索结果页面,但我不知道如何以rails方式构建查询。

例如,如果没有参数,我想返回所有结果。如果用户在搜索表单中将1到n可选参数传递给我,我想将它们添加到查询中。

接下来,如果它们具有指定的“价格说明”或“ year_built说明”或什至两者的组合。

最后使用will_paginate分开结果

# default to all listings
@listings = Mls.all

@listings.where("listing_price > ?", params[:listing_price]) unless params[:listing_price].blank?
# ... bunch of other search options ...
@listings.where("property_type = ?", params[:property_type]) unless params[:property_type].blank?

# order
@listings.order("some order by param") if some sort param
@listings.order("some order by param") if some other sort param

# paginate results
@listings.paginate(:page => params[:page])


有没有一种“路轨”方式来做到这一点?

最佳答案

您是否在高级搜索中看到了(修订的)Railscasts插曲?这里是链接:http://railscasts.com/episodes/111-advanced-search-form-revised

基本思想是创建一个Search资源,该资源将处理通过表单发送的搜索参数,并在后台对所讨论的模型进行搜索(在您的情况下为Mls

这样,您无需处理控制器中是否存在某些参数(例如params[:listing_price]),而可以处理Search模型(models / search.rb)中的条件:

def find_listings
  listings = Mls.order(:name)
  listings = listings.where("listing_price > ?", listing_price) if listing_price.present?
  # ... more condition checking
  listings
end

10-05 20:55
查看更多