Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Rails select_tag helper method

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 261
    Comment on it

    Going by my application, I have an index.html.erb file that lists all articles and i was in need of a search box that would search all articles depending on the selected category.So firstly ,I created a search box within index.html.erb like this :

     <h3> Search according to category</h3>
    
     <%= form_tag( show_category_wise_path, method: "get") do  %>
    
           <%= select_tag(:category, options_for_select(@categories.collect{ |category|   [category.category_name, category.id]})) %>
    
    
       <%= submit_tag("Search", :class => "btn btn-primary" )%>
         
     <% end %>

    Here , It is important to understand what parameters  select_tag receives. The First parameter :category provides us  a category key in our params hash for the show_category_wise action of the ArticlesController (in my case) .

    For the second parameter options_for_select method receives a collection . Here @categories object has an array of all category objects .It is something like this:

    def index
    
        @articles = Article.paginate page: params[:page] ,per_page: '2'
    
        @categories = Category.all
    
    end

    Now understand the working of collect method through this simple example:

    a = [1,2,3,4]
    
    a.collect {|x| x*2}
    

    returns [2,4,6,8].

    Remember category_name and id are columns in the categories table.So we get something like this :

    [["ruby",1],["java",2],["html",3],["c lang",4]]

    Now if user selects html , the category key in params hash  will have  value 3.Now Let's look at the show_category_wise method :

    def show_category_wise
    
        @category = Category.find(params[:category])
    
        @articles = @category.articles.paginate page: params[:page] ,per_page: '2'
    
    end

    Please take cognizance of association and pagination here .Now show_category_wise.html.erb 

    will simply list all those articles belonging to a particular category.

    Thank You.

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: