我想过滤索引页面位置和列表类别?

时间:2016-03-18 23:59:31

标签: ruby-on-rails ruby

这是我的代码:

def index
if params[:category].blank?
  @listings = Listing.all.order("created_at DESC")
else 
  @category_id = Category.find_by(name: params[:category]).id
  @listings = Listing.where(:category_id => @category_id).order("created_at DESC")
 end


if params[:location].blank?
  @listings = Location.all.order("created_at DESC")
else 
  @category_id = Location.find_by(name: params[:location]).id
  @listings = Listing.where(:location_id => @location_id).order("created_at DESC")
end

1 个答案:

答案 0 :(得分:0)

如果要按类别名称或位置名称或两者进行选择,可以有条件地将where条件应用于同一集合。

除非您想在视图中使用它们,否则无需将category_idlocation_id设为实例变量。

请注意,该示例使用#try从类别/位置检索id值,以防在类别/位置表中找不到匹配项。

def index

  @listings = Listing.all.order("created_at DESC")

  if params[:category].present?
    category_id = Category.find_by(name: params[:category]).try(:id)
    @listings = @listings.where(category_id: category_id) if category_id
  end

  if params[:location].present?
    location_id = Location.find_by(name: params[:location]).try(:id)
    @listings = @listings.where(location_id: location_id) if location_id
  end

end