轨道4嵌套表单
我有三个型号:轨道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数据?
我花了相当一段时间寻找答案,我似乎无法找到除一系列*问题之外的任何其他问题,这些问题似乎与我的问题看起来不太一样。
所有的帮助是奇妙的赞赏。
有一个有用的帖子,其中有一些例子:https://robots.thoughtbot.com/accepts-nested-attributes-for-with-has-many-through。它具体谈到在您的关联中添加inverse_of
。
在您看来,您需要使用fields_for。你可以(例如)把它放在一个表或一个列表中,并让每个条目成为一行。
如果您分享您迄今为止在您的视图中尝试过的内容,则可以在需要时获得更详细的回复。
至于在你的控制器permitted_params
,你可以嵌套他们是这样的:
def permitted_params
params.permit(item: [
:name,
item_points_attributes: [
:id,
:points,
:group_id,
]
)
end
更新:
不是fields_for(:groups)
我想你想你的控制器建立所有item_points模型(@item_points = Group.all.collect {|group| ItemPoint.new({group_id: group.id, item_id: @item.id}
)。 然后您可以使用fields_for(:item_points, @item_points)
。
您可以为该字段添加标签,使其不仅仅是使用HTML标签标签的未标记字段。
我已经添加了违规表格的一部分。感谢您一直以来的帮助。 – glapworth 2015-02-24 17:11:06
而不是'fields_for(:groups)我想你想要你的控制器为所有item_points建立模型('@item_points = Groups.collect {| group | ItemPoint.new({group_id:group.id,item_id:@item .id}')。然后你可以使用'fields_for(:item_points,@item_points)'。你可以为该字段添加一个标签,因此它不仅仅是一个使用HTML标签标签的未标记字段。 – Coenwulf 2015-02-24 19:37:40
谢谢,不要把'collect'应用到ActiveRecord模型上,它需要被应用到范围iirc – glapworth 2015-02-24 19:54:41
不是一个答案,但只是想指出,你需要在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