rails 3 has_many :through Form with checkboxes

2020-01-29 09:24发布

问题:

Asked similar before.

Rails 3 has_many :through Form

But can't get the relationship with employmentships to be created from the users form.

Have read http://www.justinball.com/2008/07/03/checkbox-list-in-ruby-on-rails-using-habtm/ and http://millarian.com/programming/ruby-on-rails/quick-tip-has_many-through-checkboxes/ (which I was really hoping that it worked.)

Form submits, but only creates a blank record in employmentship.

<%= form_for @user do |f| %>
...
<p>
   <% Company.all.each do |company| %>
        <%= check_box_tag :company_ids, company.id, @user.companies.include?(company), :name => 'user[company_ids][]' -%>
     <%= label_tag :companies_ids, company.id %>
   <% end %>
</p>
<p><%= f.submit %></p>
<% end %>

回答1:

I may be wrong, but I think that the first arg of the check_box_tag function is the actual name of the input, so instead of

check_box_tag :company_ids, company.id, @user.companies.include?(company), :name => 'user[company_ids]'

you could try something like

check_box_tag 'user[company_ids]', company.id, @user.company_ids.include?(company.id)

Let me know if it works!



回答2:

Include a hidden field tag in the form to make sure something gets submitted when none of the check boxes are selected. This should work, after the <%end%>:

<%= hidden_field_tag "user[company_ids][]" %>