活动记录查询 - 通过关联有很多

时间:2012-04-17 18:07:35

标签: ruby-on-rails ruby ruby-on-rails-3 search activerecord

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

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

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

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'

非常感谢。

罗斯

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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