Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4: checkboxes with a has_many through

I'm building an application which has to assign a assignment to multiple employers.

I have build these models:

#assignment.rb
class Assignment < ActiveRecord::Base
    has_many :employer_assignments
    has_many :employers, :through => :employer_assignments
end

#employer.rb
class Employer < ActiveRecord::Base
    has_many :employer_assignments
    has_many :assignments, :through => :employer_assignments
end

#employer_assignment.rb
class EmployerAssignment < ActiveRecord::Base
    belongs_to :employer
    belongs_to :assignment
end

And now I want the form to save to the employer_assignment table but the following code I used for my form doesn't work.

<div class="field">
    <%= f.label :employer_ids %><br />
    <%= collection_check_boxes(:assignment, :employer_ids, Employer.all, :id, :name) %>
</div>

I did add :employer_ids to my assignment controller from which I try to send the form which does create the assignment but doesn't create the records in the employer_assignment table. When I add them via the console ( Assignment.last.employers << Employer.all ) it all works fine. I'm sure I'm missing something but can't figure out what.

Thanks in advance.

like image 972
Laurens Avatar asked May 02 '13 13:05

Laurens


1 Answers

You're probably getting an Unpermitted parameters: in your log due to Strong Parameters in rails4 (@emil-kampp mentioned this), after a fresh rails generate, they are generated in your controller. So using your code it would look something like:

class EmployersController < ApplicationController
  # <snip>
  def update
    @employer.update(employer_params)
  end

  def employer_params
    params.require(:employer).permit(:name, { :employer_ids => [] })
  end
end

Also see this Question on SO which answers this. Hopefully this saves someone a few cycles.

like image 87
Karsten Avatar answered Nov 18 '22 18:11

Karsten