rails 3, checkbox association table
i have model users, type_users and details_users. an users may have many type_users and type_users may have many users. user's form is:
<div class="field">
<%= f.label :name %>
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :last_name %>
<%= f.text_field :last_name %>
</div>
<div class="field">
<% for type_user in TypeUser.all %>
<div>
<%= check_box_tag "typeuser[typeuser_ids][]",开发者_JS百科 typeuser.id %>
<%= typeuser.name %>
</div>
<% end %>
</div>
my question is:
how can i save the user(table users) and the types of users(table type_users) selected, saving the user in one table(table users), and the type of user(table details_users) on another table ?
I supose you have user_id and typeuser_id fields in your DetailsUser table so In the user controller in action create after "if @user.save"do this
if @user.save
typeusers = params[:typeuser][:typeuser_ids]
length = typeusers.length
length.times.with_index do |i|
DetailsUser.create(:user_id => @user.id, :typeuser_id => typeusers[i])
end
精彩评论