I am trying to write active record queries in my model for an advanced search.
I have a Firms model and each firm has many Categories through Categorizations
I have the following built into my search method at the moment.
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
My category schema looks like this.
create_table "categories", :force => true do |t|
t.text "name"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
and my categorizations
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
and my search form view
<div class="field">
<%= f.label :category_id, "Practice Area" %><br />
<%= f.collection_select :category_id, Category.order(:name), :id, :name, include_blank: true %>
</div>
Any ideas what I am doing wrong?
As i keep getting the error:
undefined method `categories'
Many thanks.
Ross
You are trying to run the
categoriesmethod on the array returned byfirmswhich will fail. I am assuming you want to return the firms with the given category id.