从父表单创建一定数量的子对象
感谢 Ruby on Rails:如何从表单中收集子表的值? 和“Agile Web Dev”,我知道如何使用 fields_for
在一个表单中拥有多个模型。但我正在为这件事抓狂。
假设我有一个模型 Person
。 Person
有一个 name
属性和 has_many :foos
。反过来,Foo
模型有一个 colour
属性。
此外,我知道每个Person
有恰好三个Foos
。我的模型、PersonController 中的 new 和 create 操作以及 new 视图应该是什么样子,以便呈现三个标签精美的文本输入框,每个 Foo 一个,并且能够报告验证错误,以允许我的“新人”表单一次性创建整套四个对象?
另外,我可以在没有 accepts_nested_attributes_for
的情况下执行此操作吗?
Thanks to Ruby on Rails: How to gather values for child tables from a form? and "Agile Web Dev", I know how to have multiple models in a form using fields_for
. But I'm tearing my hair out over this one.
Suppose I have a model Person
. Person
has a name
attribute, and has_many :foos
. The Foo
model, in turn, has a colour
attribute.
Furthermore, I know that each Person
has precisely three Foos
. What should my Models, the new
and create
actions in PersonController
, and the new
view look like in order to present three nicely-labelled text-entry boxes, one for each Foo and capable of reporting validation errors, to allow my "new person" form to create the whole set of four objects in one go?
Also, can I do this without accepts_nested_attributes_for
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在尝试了不同位置的方括号和不同的 for 循环之后,我想我已经解决了这个问题。这是我的代码现在的样子(根据脚手架设置路由,以便从
/new
发布会触发create
)。models/person.rb
models/foo.rbcontrollers
/people_controller.rbviews
/people/new.html.erb
这似乎可以解决问题。
After some playing about with varied locations for square braces and different for loops, I think I've solved this. Here's what my code looks like now (with routes set up as per scaffolding, so that posting from
/new
triggerscreate
).models/person.rb
models/foo.rb
controllers/people_controller.rb
views/people/new.html.erb
This seems to do the trick.