Search code examples
ruby-on-railsruby-on-rails-3ruby-on-rails-3.1

Rails Radio button link to controller action


How can I set a selected radio button in my view to perform an action in my controller. For example, I have 3 search actions defined in my controller, and I would like the user to select a radio button which would route the search query to the appropriate controller action.


Solution

  • You can pass two params to your controller, the search and the option for example:

    <%= form_tag controller_path, method: :get do %>
      <%= text_field_tag :search, params[:search] %>
        <%= label_tag :option1 %>
        <%= radio_button_tag :option, "1" %>
        <%= label_tag :option2 %>
        <%= radio_button_tag :option, "2" %>
        <%= label_tag :option3 %>
        <%= radio_button_tag :option, "3" %>
      <%= submit_tag "Search", name: nil %>
    <% end %>
    

    So, it will send through the URL the search= and the option= with some values, for example search=some+test and option=1.

    Then, in your controller, you can work with these two params.... for example:

    if params[:option] == "1"
      #do something using the params[:search]
    elsif params[:option] == "2"
      #do something using the params[:search]
    elsif params[:option] == "3"
      #do something using the params[:search]
    else
      #do something else
    ...
    

    I hope it helps...