我有三个型号:轨道4嵌套表单
class Item < ActiveRecord::Base
has_many :item_points
has_many :groups, through: :item_points
accepts_nested_attributes_for :item_points
end
class ItemPoint < ActiveRecord::Base
belongs_to :group
belongs_to :item
accepts_nested_attributes_for :group
end
class Group < ActiveRecord::Base
has_many :item_points
has_many :items, through: :item_points
end
为items
create_table "items", force: :cascade do |t|
t.string "name", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
架构的架构item_points
create_table "item_points", force: :cascade do |t|
t.decimal "points", null: false
t.integer "item_id", null: false
t.integer "group_id", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
的架构groups
create_table "groups", force: :cascade do |t|
t.string "name", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
在我的groups
表中,我创建了许多行,例如, 组1和组2。
在表单创建items
我很想看到每个字段为group 1
和group 2
,这样我也许能为该项目进入点。例如在项目X中,组1是10分,组2是5分。
编辑添加的形式
形式:
<%= form_for(@item) do |item_form| %>
<div class="form-group">
<%= item_form.label :name %>
<%= item_form.text_field :name, :class => 'form-control' %>
</div>
<%= item_form.fields_for(:groups) do |groups_form| %>
<% group = groups_form.object_id.to_s%>
<%= groups_form.hidden_field :id %>
<%= groups_form.fields_for(:item_point) do |entity_form| %>
<%= entity_form.text_field :points %>
<% end %>
<% end %>
这为我提供了一个表格,其中包含一个额外的输入框,称为item[groups][item_point][points]
,并且没有标签。
我想知道的是,我如何获得全部我已经添加到组中的行作为字段到Rails表单中?当我这样做时,如何使用强参数保存关联的item_points数据?
我花了相当一段时间寻找答案,我似乎无法找到除一系列StackOverflow问题之外的任何其他问题,这些问题似乎与我的问题看起来不太一样。
所有的帮助是奇妙的赞赏。
不是一个答案,但只是想指出,你需要在item_points表中将group_id更改为item_group_id,或将'foreign_key:group_id'添加到'belongs_to:item_group' – Coenwulf 2015-02-24 15:57:22
谢谢。这是我的错字:) – glapworth 2015-02-24 16:05:43