我有一个创建“人才文件”的表单。在这种形式中,作为单独模型的属性是“高度、体重、头发等”。对于人才概况。然而,这实际上涉及到4张表。
带有示例的表格
人才简介
id - 1
talent_profile_attributes -(将人才链接到具有值的属性)
Talent_id - 1
default_attribute_id - 2
default_attribute_value_id - 3
default_attributes -
id - 2
姓名 - “头发”
default_atrribute_values -
id - 3
default_attribute_id - 2
值-“棕色”
与模型的关系很好,我可以手动插入表中并根据需要检索每个配置文件的属性。但是,我遇到的问题是弄清楚如何以单一表单提交 TalentProfile 模型和 TalentProfileAttributes 模型。
我尝试使用accepts_nested_attributes_for,但没有成功。此外,我不太确定如何将 default_attribute_id 和 default_attribute_value_id 放入表单的字段中。任何想法或方向将不胜感激,现在已经研究了几个小时但无济于事。
基本上,我正在寻找一个显示 DefaultAttributes 表中所有值的表单,其中的下拉列表包括每个属性的 DefaultAttributeValue,并在提交时在 TalentProfileAttribute 表中创建关系。
最佳答案
弄清楚了,在模型、 View 和 Controller 中使用了它
型号
accepts_nested_attributes_for :talent_profile_attributes
Controller
def new
@talent = TalentProfile.new
@attributes = DefaultAttribute.all
@attributes.count.times { @talent.talent_profile_attributes.build }
end
查看
<% attr_i = DefaultAttribute.first.id - 1 %>
<%= f.fields_for :talent_profile_attributes do |attrf| %>
<%= attrf.label :default_attribute_value_id, @attributes[attr_i].name %>
<%= attrf.select :default_attribute_value_id,
@attributes[attr_i].default_attribute_values.collect {|p| [ p.value, p.id ] }.unshift("-") %>
<%= attrf.hidden_field :default_attribute_id, value: @attributes[attr_i].id %>
<% attr_i += 1 %>
<% end %>
关于mysql - Rails 4 一种形式的多个模型,包括键值表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21066607/