【问题标题】:Rails 4.2 saving has_and_belongs_to_many association IdsRails 4.2 保存 has_and_belongs_to_many 关联 ID
【发布时间】:2015-07-11 02:46:11
【问题描述】:

我的以下代码在带有 protected_attributes gem 的 Rails 4.1 中运行良好(我的代码还没有移动到 strong_parameters)

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

我在更新员工时将技能绑定到员工,因此我的视图如下所示

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 是 attr_accessible 参数的一部分,因此它在保存员工表单的同时完美运行。 (注意:这甚至不需要 accept_nested_attributes_for :skills 在员工模型中设置)

导轨 4.2

我正在将我的代码迁移到 Rails 4.2 并迁移到强参数。

我已将员工控制器中的技能 ID 列入白名单,并在更新操作中调用它,如下所示:

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

但它不会更新员工的技能 ID。

谁能指出 Rails 4.2 中保存此类关联值的变化?

谢谢。

【问题讨论】:

    标签: ruby-on-rails nested-forms has-and-belongs-to-many ruby-on-rails-4.2


    【解决方案1】:

    问题是我如何将参数列入白名单。它应该像这样作为数组参数被列入白名单:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多