Pregunta

I have a view like this

<%= form_tag member_survey_path(@survey), :method => :post do %>
 <% @survey.each do |s| %>
  <td><%= s.title %></td>
  <td><%= select_tag 'survey[][status]', options_for_select([['AAA',"0"],['DDD',"1"],['BBB',"2"],['CCC',"3"]]) %> </td>
 <% end %>
<%= submit_tag 'submit', :class => "btn new_btn" %>
<% end %>

I have no idea how to do in the controller, and how to pass the survey.id

¿Fue útil?

Solución

Change the name attribute of your select tag to have the id of each survey:

<%= select_tag "survey[#{s.id}][status]" ....

This will build a params structure like this:

params = {:survey => {123 => {:status => 0}, 21 => {:status => 1}, 36 => {:status => 0}}} 

where 123, 21 & 36 are the ids of survey objects. Then, in your controller you can do this:

params[:survey].each do |survey_id, attributes|
  if survey = Survey.find_by_id(survey_id)
    survey.update_attributes(attributes)
  end 
end

If you want to make anything else editable in the survey within that form, it's easy to do: eg if you wanted to edit the name as well, you could just add

<td><%= text_field_tag "survey[#{s.id}][name]", s.name %></td>

which would make a params structure like

    params = {:survey => {123 => {:status => 0, :name => "foo"}, 21 => {:status => 1, :name => "bar"}, 36 => {:status => 0, :name => "baz"}}} 

and you still have all the attributes for the survey neatly contained in a single hash.

As an aside, it's not good practice to call variables things like "s" as it doesn't tell the reader (which could include you in the future) what it is. Rails convention is to name active record objects after their class, so you would say

@surveys.each do |survey|
   ..etc
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top