从表单创建 has_many 关系 [英] Create has_many relationships from form

查看:31
本文介绍了从表单创建 has_many 关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以如果我有两个这样的模型:

So if I have a two models like this:

#parent.rb
class Parent < ApplicationRecord
    has_many :children
end

#children.rb
class Child < ApplicationRecord
    belongs_to :parent
end

您将如何创建允许您在创建父级的表单中创建多个子级的表单?

How would you create a form that allows you to create multiple children in the form that creates the parent?

推荐答案

Cocoon[0] 很好地解决了这个问题,并且有一个很棒的示例应用程序.

Cocoon[0] solves this problem quite nicely, and has a great example app.

在后端滚动,在您的 Parent 模型上抛出 accepts_nested_attributes_for :children,执行一些 fields_for(或 simple_fields_for) 内容,并确保您可以通过将 children_attributes: [:name, :age] 添加到您的 parent_params 来分配属性.

Rolling on the back-end, throw accepts_nested_attributes_for :children on your Parent model, do some fields_for (or simple_fields_for) stuff in your form, and make sure you can assign the attributes by adding children_attributes: [:name, :age] to your parent_params.

[0] https://github.com/nathanvda/cocoon

这篇关于从表单创建 has_many 关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆