Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails 3 has_many :through Form with checkboxes

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 %>
like image 375
pcasa Avatar asked Feb 20 '11 01:02

pcasa


1 Answers

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][]" %>
like image 58
Francis Potter Avatar answered Oct 06 '22 00:10

Francis Potter