简体   繁体   中英

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.

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

 params.require(:employee).permit({:skill_ids => []}, .....)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM