我正在尝试根据category_id
和sub_category_id
过滤结果。
代码行如下:
@wanted_equipments = WantedEquipment.all.filter(params.slice(:category_id)).order("created_at desc").page(params[:page]).per(per_page_items)
这一行基于category_id
完美过滤,但是一旦我也包含sub_category_id
,如下所示:
@wanted_equipments = WantedEquipment.all.filter(params.slice(:category_id, :sub_category_id)).order("created_at desc").page(params[:page]).per(per_page_items)
这让我错误地说:
undefined method `sub_category_id' for #<WantedEquipment::ActiveRecord_Relation:0x007fb294732870>
我使用Model.where
方法调试它,传递相同的category_id
和sub_category_id
。它给了我基于类别id和子类别id我传递的结果。调试代码如下:
x = params[:category_id]
y = params[:sub_category_id]
if x.present? && y.present?
@wanted_equipments = WantedEquipment.where(category_id: "#{x}", sub_category_id: "#{y}")
end
但是当我传递与调试代码中相同的sub_category_id时,我在此行中收到错误:
@wanted_equipments = WantedEquipment.all.filter(params.slice(:category_id, :sub_category_id)).order("created_at desc").page(params[:page]).per(per_page_items)
关注的过滤方法:
module Filterable
extend ActiveSupport::Concern
module ClassMethods
def filter(filtering_params)
results = self.where(nil)
filtering_params.each do |key, value|
results = results.public_send(key, value) if value.present?
end
results
end
end
end
如果需要更多信息,请发表评论。