Kosmonaut
Kosmonaut

Reputation: 2290

How can I edit a single field for an array of object?

I'm trying to edit a collection of users. I want to render table with a list of names and checkboxes. I'm close, but I'm missing something.

My form looks like so:

<%= form_for 'users[]', :url => approve_users_path, :html => {:class => 'form-horizontal'} do |f| %>
<tbody>
  <% for user in @users %>
    <%= fields_for user do |u| %>
      <tr>
        <td><%= user.name %></td>
        <td><%= u.check_box :vouched %></td>
      </tr>
   <% end %>
  <% end %>
</tbody>
<% end %>

which generates

<tr>
  <td>steve cabillero</td>
  <td><input name="user[vouched]" type="hidden" value="0" /><input id="user_vouched" name="user[vouched]" type="checkbox" value="1" /></td>

however, I need the input name in the form of users[id][vouched] and vouched is a virtual attribute.

when I try to use f.check_box I get a method not found error.

Upvotes: 0

Views: 75

Answers (1)

jvnill
jvnill

Reputation: 29599

you should use form_tag if you are not using a specific resource in the form. I also suggest using #each instead of a for loop and check_box_tag for the checkbox

<%= form_tag approve_users_path, :class => 'form-horizontal' do %>
  <tbody>
    <% @users.each do |user| %>
      <tr>
        <td><%= user.name %></td>
        <td><%= check_box_tag "users[#{user.id}][vouched]" %></td>
      </tr>
    <% end %>
  </tbody>
<% end %>

Upvotes: 1

Related Questions