具有一对一关系的嵌套属性
我现在坐在这里 8 个小时来弄清楚它是如何工作的:我正在尝试修改 http://asciicasts.com/episodes/196-nested-model-form-part-1 变为一对一关系。
class Survey < ActiveRecord::Base
has_one :question, :dependent => :destroy
accepts_nested_attributes_for :question
end
class Question < ActiveRecord::Base
belongs_to :survey
end
控制器:
def new
@survey = Survey.new
@survey.questions.build
end
如果我使用一对多关系,效果会很好,例如:
class Survey < ActiveRecord::Base
has_many :questions, :dependent => :destroy
accepts_nested_attributes_for :questions
end
我做错了什么?
I'm sitting here now for 8 hours to figure out how that works: I'm trying to modify the example in http://asciicasts.com/episodes/196-nested-model-form-part-1 into a one-to-one relationship.
class Survey < ActiveRecord::Base
has_one :question, :dependent => :destroy
accepts_nested_attributes_for :question
end
class Question < ActiveRecord::Base
belongs_to :survey
end
Controller:
def new
@survey = Survey.new
@survey.questions.build
end
It works great if I use a one-to-many relationship like:
class Survey < ActiveRecord::Base
has_many :questions, :dependent => :destroy
accepts_nested_attributes_for :questions
end
What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试使用 @survey.build_question 而不是 @survey.questions.build。
我认为当你使用一对一关系时,这是提出问题的正确方法。
Try @survey.build_question instead of @survey.questions.build.
I think that is the right way to build questions when you use a one-to-one relationship.