我正在尝试使用form_for创建一个表单,该表单将添加Employees。对于员工,我想动态分配多个特殊化,如c#,asp等。我在表单中使用以下代码
<%= f.select :specilization, Specialization.all.collect{|p| [p.name, p.id]}, {}, :multiple => true %>
我还在员工和专业化之间制定了HABTM,如
Employee.rb
class Employee < ActiveRecord::Base
has_and_belongs_to_many :specializations
end
Specialization.rb
class Specialization < ActiveRecord::Base
has_and_belongs_to_many :employees
end
完成这些操作后,我无法在db(MySQl)中保存所选值。如果有人能解决我的问题或指导我如何做到这一点,我将不胜感激?
提前致谢。
答案 0 :(得分:0)
我通常使用has_many :through
解决此问题,然后在我的表单中,select是连接模型上的field_for
。像这样:
class Employee < ActiveRecord::Base
has_many :employees_specializations
has_many :specializations, through: :employees_specializations
# we will be creating these join models on the employee form
accepts_nested_attributes_for :employees_specializations
end
class Specialization < ActiveRecord::Base
has_many :employees_specializations
has_many :employees, through: :employees_specializations
end
class EmployeesSpecialization < ActiveRecord::Base
belongs_to :employee
belongs_to :specializations
end
现在重要的是要注意,通过这种简化的方法,我假设数据库中已存在专业化,我们只是选择它们并将它们加入我们正在创建/编辑的员工中:
# in your controller make sure to build at least 1 new instance, the fields_for needs this
@employee.employees_specializations.build
# remember to add to your strong parameters the new join attributes
params.require(:employee).permit(
# ... other attributes ...
employees_specializations_attributes: [:id, :specialization_id]
)
您需要将:id, :specialization_id
声明为子字段,因为employees_specializations_attributes
将是嵌套的哈希,其中包含这些键。
# now in your form use fields_for
<%= f.fields_for :employees_specializations do |ef| %>
<%= ef.select :specialization_id, Specialization.all.map{|p| [p.name, p.id]}, {}, multiple: true %>
<% end %>
f.fields_for :employees_specializations
将创建名为employee[employees_specializations_attributes][][specialization_id]
的表单字段。这基本上表示我们正在创建嵌套关联employees_specializations
并将嵌套关联的specialization_id
(请记住employees_specialization belongs_to :specialization
)设置为所选的特化。请注意字段名称中间的[]
,这意味着它是一个嵌套的employees_specializations
数组。
发布并禁止任何验证错误,您应该能够创建/编辑员工并通过从现有专业列表中选择并在它们之间创建连接模型来设置其专业化。
进一步阅读: