这是我的代码:
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
端
答案 0 :(得分:0)
如果要按类别名称或位置名称或两者进行选择,可以有条件地将where
条件应用于同一集合。
除非您想在视图中使用它们,否则无需将category_id
或location_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