模型的未定义方法`sub_category_id'

时间:2017-03-25 09:57:26

标签: ruby-on-rails ruby activerecord

我正在尝试根据category_idsub_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_idsub_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

如果需要更多信息,请发表评论。

0 个答案:

没有答案