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

how to pass params from radio_button_tags to controller


Here is my form that displays all the feedbacks that was not reviewed yet by admin:

I have 2 radio buttons next to each feedback to select accept or denied with values 1 or 2.

<% form_tag moderate_feedbacks_path, :method => :put do %>
  <table>
    <% @all_feedbacks.each do |feedback| %>
    <tr>
      <td><%= radio_button_tag :review_option, '1', false, :name => feedback.id %></td>
      <td><%= radio_button_tag :review_option, '2', false, :name => feedback.id %></td>
      <td><%= feedback.name %></td>
      <td><%= feedback.email %></td>
      <td><%= feedback.message %></td>
    </tr>
    <% end %>
   </table>
<%= submit_tag 'Apply' %>
<% end -%>

what I want to do is when I click submit_tag, to update the review_option field for each selected feedback with the value of that radio_button_tag, 1 or 2

I have by now the form as you see it, works good, but I am stuck at the controller part:

def moderate_feedbacks
  Feedback.update_all(["review_option = ?", ????])
  redirect_to admin_feedbacks_path
end

how do I pass the params from those radio buttons to the controller. Thank you.

p.s. html source:

<input id="review_option_1" name="3" type="radio" value="1">
<input id="review_option_2" name="3" type="radio" value="2">

name is taken from feedback.id

logs when I press the submit_tag looks like this;

Processing Admin::FeedbacksController#moderate_feedbacks (for 127.0.0.1 at 2012-10-16 15:36:20) [PUT]
  Parameters: {"commit"=>"Apply", "3"=>"2", "4"=>"1"}

where 3 is the id of feedback - 2 the radio value, 4 is the id of feedback - 1 the radio value

after raise.params["feedback.is"].inspect

Parameters:

    {"commit"=>"Apply",
     "3"=>"1",
     "4"=>"1",
     "_method"=>"put"}

Solution

  • ok, so here is the answer:

    in the feedback.rb

       class Status
         ACCEPTED = 1
         REJECTED = 2
       end
    

    in the form:

    <% form_tag moderate_feedbacks_path, :method => :put do %>
      <table>
        <% @all_feedbacks.each do |feedback| %>
        <tr>
          <td><%= radio_button_tag :review_option, Feedback::Status::ACCEPTED, false, :name => feedback.id %></td>
          <td><%= radio_button_tag :review_option, Feedback::Status::REJECTED, false, :name => feedback.id %></td>
          <td><%= feedback.name %></td>
          <td><%= feedback.email %></td>
          <td><%= feedback.message %></td>
        </tr>
        <% end %>
       </table>
    <%= submit_tag 'Apply' %>
    <% end -%>
    

    in the feedbacks_controller.rb

       def moderate_feedbacks
        params.each do |key, value|
          if key =~ /^r(\d+)/ && !value.blank?
            feedback_id = $1
            Feedback.update_all(["review_option = ?", value.to_i], ["id = ?", feedback_id])
          end
        end
        redirect_to admin_feedbacks_path
      end