0

我正在尝试在我的模型中编写活动记录查询以进行高级搜索。

我有一个公司模型,每个公司通过分类有许多类别

目前,我的搜索方法中内置了以下内容。

def find_firms
    firms = Firm.order(:name)
    firms = firms.where("name like ?", "%#{name}%") if name.present?
    firms = firms.categories.find(id: category_id) if category_id.present?
end

我的类别架构如下所示。

create_table "categories", :force => true do |t|
  t.text     "name"
  t.datetime "created_at", :null => false
  t.datetime "updated_at", :null => false
 end

和我的分类

 create_table "categorizations", :force => true do |t|
   t.integer  "category_id"
   t.integer  "firm_id"
   t.datetime "created_at",  :null => false
   t.datetime "updated_at",  :null => false
 end

和我的搜索表单视图

  <div class="field">
    <%= f.label :category_id, "Practice Area" %><br />
    <%= f.collection_select :category_id, Category.order(:name), :id, :name, include_blank: true %>
  </div>

任何想法我做错了什么?

当我不断收到错误消息时:

 undefined method `categories'

非常感谢。

罗斯

4

2 回答 2

1

将您的功能更改find_firm为:

 def find_firms
    if category_id.present?
      if name.present?
        Firm.where("name like ?", "%#{name}%").joins("JOIN categorizations ON firms.id = categorizations.firm_id").where("categorizations.category_id = ?", category_id).order(:name)
      else
        Firm.joins("JOIN categorizations ON firms.id = categorizations.firm_id").where("categorizations.category_id = ?", category_id).order(:name)
    elsif name.present?
      Firm.where("name like ?", "%#{name}%").order(:name)
    else
      Firm.order(:name)
    end
  end
于 2012-04-17T18:12:00.667 回答
1

您正在尝试在categories返回的数组上运行该方法,该方法firms将失败。我假设您要返回具有给定类别 ID 的公司。

def find_firms
  firms = Firm.order(:name)
  firms = firms.joins(:categories).
            where(:categories =>{ id : category_id}).uniq if category_id.present?
  firms = firms.where("name like ?", "%#{name}%") if name.present?
end
于 2012-04-17T18:30:52.143 回答