I have two main models in my app, "Business" and "Category". I currently have a search text_field that works just fine, but I am also trying to implement the ability for users to search for Businesses that 'belongs_to' a certain category based on a collection_select containing the available categories.
I have the collection_select working, but I can not seem to figure out how to get it to show the businesses that 'belongs_to' the chosen category.
Here is the search info in my Business Controller:
def search
if params[:search].present?
@businesses = Business.search(params[:search])
else
@businesses = Business.all.paginate(page: params[:page], per_page: 6)
end
end
My search form:
<%= form_tag search_businesses_path, method: :get, role: "search", :class => "search" do %>
<%= label :category, "Search By Business Name" %>
<%= text_field_tag :search, params[:search], id: "search", :placeholder => 'Search Business' %>
<%= button_tag(type: 'submit', class: "button") do %>
<i class="fa fa-arrow-right"></i>
<% end %>
<% end %>
And my current category collection select:
<%= form_for :category do |f| %>
<%= f.label :category, "Search By Category" %><br>
<%= f.collection_select :category_id, Category.all.order('name ASC'), :id, :name %>
<%= button_tag(type: 'submit', class: "button") do %>
<i class="fa fa-arrow-right"></i>
<% end %>
<% end %>
I know that I need to tell the collection select that it needs to display the businesses, but I can't seem to figure out how to properly implement it.
UPDATE
I tried the following code and no results appear:
My Business Model
def search_data
{
name: name,
category_id: category_id
}
end
My Business Controller
def search
if params[:search].present?
@businesses = Business.search "apples", where: { category_id: params[:category_id] }
else
@businesses = Business.all.paginate(page: params[:page], per_page: 6)
end
end
My Form
<%= form_tag search_businesses_path, method: :get, role: "search", :class => "search" do %>
<%= label :category, "Search By Category" %>
<%= collection_select :search, params[:category_id], Category.all.order('name ASC'), :id, :name %>
<%= button_tag(type: 'submit', class: "button") do %>
<i class="fa fa-arrow-right"></i>
<% end %>
<% end %>