Search code examples
ruby-on-rails-4search-form

Rails 4 Search By Category


I want to put a search form on my homepage at pages#home. I'd like to be able to search my model by category. I haven't been able to find a solution where you're actually putting the logic on a different controller than the models you're searching on. I was wondering if someone could help with the syntax and where it needs to go. Here are my relations:

vendor.rb

class Vendor < ActiveRecord::Base
  validates :category_id, presence: true
  belongs_to :category
end

category.rb

class Category < ActiveRecord::Base
  has_one :vendor
end

pages_controller.rb

def home
  @vendors = Vendor.all
end

routes.rb

root 'pages#home'

I'm trying to put the search form on home.html.erb, which is under the pages layouts. Was hoping someone could help with how I can accomplish this. This being (seemingly) a simple type of search, I'd hopefully not have to use a gem.

EDIT: ANSWER For those searching, here's what worked. Thank you @Vla

vendors_controller.rb

def search
  @vendors = Vendor.search(params)
end

pages/home.html.erb (this is my root 'pages#home')

<%= form_tag vendors_search_path, method: :get do |f| %>
  <%= text_field_tag :search, params[:search], placeholder: "Search Vendors" %>
  <%= select_tag 'category', options_for_select(Category.all.map{|el| [el.name, el.id]}) %>
  <%= submit_tag 'Search' %>
<% end %>

routes.rb (make sure to put this near the top)

get 'vendors/search'

vendors/search.html.erb

<% @vendors.each do |vendor| %>
  <%= vendor.name %>
  <%= vendor.phone %>
  <%= vendor.email %>
<% end %>

Solution

  • Ok, You can do it this way:

    Go to Your vendor.rb file and add search method like this:

    def self.search params    
      vendors = Vendor.where(category_id: params[:category].to_i) unless params[:category].blank?
      vendors
    end
    

    Then in Your vendors_controller create search method:

    def search
      @vendors = Vendor.search(params)
    end
    

    Then create form at homepage similar to:

    = form_tag search_vendors_path, method: :get, role: 'form' do
      .form-group
        %label Category
        = select_tag 'category', options_for_select(Category.all.map{|el| [el.name, el.id]}), class: 'form-control'
        = submit_tag 'Search'
    

    And do not forget to put

    get  'vendors/search'
    

    into Your routes and add "search" view.

    You can still do the same without search action, with result on Your homepage. Anyway I hope You got the idea.