我有三個型號:軌道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