Rails 3:通过子级的“嵌套表单”创建父级
class Parent
has_many :children
end
class Child
belongs_to :parent
accepts_nested_attributes_for :parent
end
该表单是通常的嵌套表单,但从孩子的角度来看:
=nested_form_for @child do |f|
=f.fields_for :parent
…
我想让用户从带有父母姓名的选择菜单中进行选择。如果需要的话,还可以让他们创建新的父记录。 那么,如果子表单尚不存在,如何从子表单创建一个父表单呢?
class Parent
has_many :children
end
class Child
belongs_to :parent
accepts_nested_attributes_for :parent
end
The form is the usual nested form, but from the Child's perspective:
=nested_form_for @child do |f|
=f.fields_for :parent
…
I'd like to let users choose from a select menu with Parents names. And additionally enable them to create a new Parent record if needed.
So how to create a Parent from the child's form if it doesn't yet exist?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当用户从选择菜单中选择“创建新”时,您可以使用 javascript 在窗口/层中弹出父创建表单,然后让返回结果使用新添加的父项的新父项列表重新渲染nested_form已经选择了。
同样的原则在没有 JavaScript 的情况下也适用,尽管您可能需要一个“添加新父级”按钮,该按钮可以转到新的父表单,然后在创建时重定向回已选择新父级的子表单。
You could use javascript to pop up the parent create form in a window/layer when the users select 'create new' from the select menu and then have the return result re-render the nested_form with the new list of parents with the newly added parent already selected.
The same principles apply without javascript, though you probably need a 'Add new parent' button that goes to the new parent form and then redirects back to the child form on creation with the new parent already selected.