Rails search form for multiple column in a table

1.5k views Asked by At

I have a simple rails search form that will select rank on a column in which 3 different ranks in a table. But I cannot extend plural ranks.


Table Food: value1, rank_value1, value2, rank_value2, value3, rank_value3

View /foods/index.html:

<%= form_tag foods_path, :method => 'get' do %> 
  <p>
    rank_value1
    <%= text_field_tag :rvalue1, params[:rvalue1] %>
    <%= submit_tag "Search", :name => nil %>
 </p>
<% end %>

Model food.rb:

def self.search(search) 
    if search 
      Food.where(["rank_value1= ?", "#{search}"])
    else
      Food.all
    end
end

Controller foods_controller.rb:

def index
   @foods = Food.search(params[:rvalue1])
end

To extend two ranks, I tried codes below but it did not work.

View /foods/index.html:

<%= form_tag foods_path, :method => 'get' do %> 
  <p>
    rank_value1
     <%= text_field_tag :rvalue1, params[:rvalue1] %>
     <%= text_field_tag :rvalue2, params[:rvalue2] %>
    <%= submit_tag "Search", :name => nil %>
  </p>
<% end %>

Model food.rb:

def self.search(search1,search2) 
    if search 
      Food.where(["rank_value1= ? and rank_value2=?", "#{search1}", "#    {search2}"])
    else
      Food.all
    end
end

Controller foods_controller.rb:

def index
  @foods = Food.search(params[:rvalue1], params[:rvalue2])
end

Any suggestions as to search with data in multiple columns?

1

There are 1 answers

0
Bhavesh Waghela On

Hey for searching with multiple values you can use Ransack gem. Here you can see the video tutorial and github link for implementation.

github: https://github.com/activerecord-hackery/ransack

video : http://railscasts.com/episodes/370-ransack

Hope you are looking for this only.