开发者

fields_for with association question

开发者 https://www.devze.com 2023-02-14 01:05 出处:网络
How do I开发者_JAVA百科 use association data from within a fields_for? I\'ve got a has many through relationship between users, schools and schools_users. A user can have multiple schools and a schoo

How do I开发者_JAVA百科 use association data from within a fields_for?

I've got a has many through relationship between users, schools and schools_users. A user can have multiple schools and a school has multiple users. In schools_users there is a user_role field in addition to the common user_id and school_id.

In the show view I have:

<% @school.schools_users.each do |user| %>
<tr><td><%= user.user.first_name %> <%= user.user.last_name %></td><td><%= user.user_role %></td></tr>
<% end %>

but I can't figure out how to do the same thing from within the fields_for on the edit page.

<%= f.fields_for :schools_users do |f| %>
    <tr>
        <td><%= NEED USER NAME HERE %></td>
        <td><%= f.select(:user_role, active_role_options)%></td>
        <td><%= link_to_remove_fields 'Delete', f %></td>
    </tr>
<% end %>

Thanks for any help!


Firstly: You're assigning the block variable of your fields_for to f, which is the same f your form_for uses. You should use a different name, like user_fields.

With that:

<%= f.fields_for :schools_users do |user_fields| %>
  <tr>
    <td><%= user_fields.text_field :first_name %></td>
    ...
<% end %>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号