Rails 嵌套属性

发布于 2024-09-03 06:17:20 字数 612 浏览 4 评论 0原文

我正在使用 Rails 3.0.0.beta3,并且尝试使用 :accepts_nested_attributes_for 来实现具有嵌套属性的表单。

我的表单嵌套在三个级别:调查>>问题>>回答。

调查有很多问题,问题有很多答案。

在调查模型中,有 :accepts_nested_attributes_for :questions

在问题模式中,有 :accepts_nested_attributes_for :answers

一切正常,除了当我向现有问题添加新答案时,它不会被创建。但是,如果我在创建答案时对相应的问题进行更改,我就可以成功创建答案。

这个例子与railscast完全相似: http://railscasts.com/episodes/197-nested-model- form-part-2

但在rails3中不起作用(至少在我的情况下)。

如果 Rails 3 中的嵌套属性有任何问题,请告诉我。

提前致谢。

I am using rails 3.0.0.beta3 and I am trying to implement form with nested attributes using :accepts_nested_attributes_for.

My form is nested to three levels: Survey >> Question >> Answer.

Survey has_many Questions, and Question has many Answers.

Inside the Survey model, there is
:accepts_nested_attributes_for :questions

and inside the question mode, there is
:accepts_nested_attributes_for :answers

Everything is working fine except when I add a new answer to an existing question, it doesn't get created. However, if I make changes to the corresponding question while creating the answer, I can successfully create the answer.

This example is exactly similar to a railscast:
http://railscasts.com/episodes/197-nested-model-form-part-2

but doesn't work in rails3 (at least in my case).

Please let me know if there is any issue with nested attributes in Rails 3.

Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

表情可笑 2024-09-10 06:17:20

如果您使用的是attr_accessible,请确保包含嵌套属性。

class Survey < ActiveRecord::Base
  accepts_nested_attributes_for :questions
  attr_accessible :questions_attributes
end

class Question < ActiveRecord::Base
  accepts_nested_attributes_for :answers
  attr_accessible :answers_attributes
end

如果您仍然遇到问题,请参阅此处有关嵌套属性和模型验证的评论。 具有多个模型的表单中的验证失败

If you are using attr_accessible make sure that you include the nested attributes

class Survey < ActiveRecord::Base
  accepts_nested_attributes_for :questions
  attr_accessible :questions_attributes
end

class Question < ActiveRecord::Base
  accepts_nested_attributes_for :answers
  attr_accessible :answers_attributes
end

Also, see my comment here about nested attributes and model validations if you are still having trouble. Validations misfiring in a form with multiple models

随风而去 2024-09-10 06:17:20

看看那个railscast 上的评论93(作者:Casper Fabricus)。他说你必须在助手的“link_to_add_fields”方法中将“[]”放在“new_object”周围。

也许这就是你所击中的?

Take a look at comment 93 on that railscast (by Casper Fabricus). He says you have to put "[]" around "new_object" in the "link_to_add_fields" method in helper.

Maybe that's what you're hitting?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文