Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4.2 saving has_and_belongs_to_many association Ids

I have the following bit of code that is working fine with Rails 4.1 with protected_attributes gem (I didn't have my code moved to strong_parameters yet)

models/employee.rb

class Employee

   has_and_belongs_to_many :skills

   attr_accessible :skill_ids, ...

end

models/skill.rb

class Skill
  has_and_belongs_to_many :employees
end

I bind the skills to the employee while updating an employee so my view looks like below

views/employees/_form.html.erb

 <%= form_for @employee,  do |f| %>
.....

  <%= f.collection_select :skill_ids, Skill.all, :id, :name, {}, 
    {:multiple => true, class: 'select2 '} %>
......
<% end %>

skill_ids were part of attr_accessible params so it worked perfectly while saving the employee form. (Note: this doesn't even require accepts_nested_attributes_for :skills set at the employee model)

Rails 4.2

I am in the process of migrating my code to Rails 4.2 and moving to strong parameters.

I've white-listed the skill_ids in the employees controller and invoking that on the update action, like so :

controllers/employee_controller.rb

def update
  @employee = Employee.find(params[:id])
  @employee.update_attributes(employee_params)
end

private 
def employee_params
  params.require(:employee).permit(:skill_ids, .....)
end

But it just wouldn't update the skill ids for the employees.

Can someone please point me what has changed in Rails 4.2 for saving association values like these?

thanks.

like image 248
thanikkal Avatar asked Jul 11 '15 02:07

thanikkal


1 Answers

The issue was how I whitelisted the param. It should be whitelisted as an array param like so:

 params.require(:employee).permit({:skill_ids => []}, .....)
like image 140
thanikkal Avatar answered Nov 15 '22 08:11

thanikkal