[英]ruby on rails- nested attributes for 'has_one' relationship
I need some help concerning nested attributes in models with 'has_one' relationship. 我需要有关具有“ has_one”关系的模型中的嵌套属性的一些帮助。
Model Survey has 1 question Model Question has 1 answer 模型调查有1个问题模型问题有1个答案
How do i build the 'answer' in the code below 如何在下面的代码中构建“答案”
def new
@survey = Survey.new
@survey.build_question # build one question
@survey.question.answer.build #this part is not working
end
Please can anybody tell me how to build the answer as the code "@survey.question.answer.build" is not correct. 有人可以告诉我如何构建答案,因为代码“ @ survey.question.answer.build”不正确。
Many many thanks for your help 非常感谢您的帮助
You must build the answer on the newly created Question
instance since it's not yet been saved. 由于尚未保存新创建的
Question
实例,因此必须在其上构建答案。
@survey = Survey.new
@question = @survey.build_question
@answer = @question.build_answer
# ... at some point in the future
@survey.save
@survey = Survey.new
@survey.question = Question.new
@survey.question.answer = Answer.new
@survey.question.answer = (whatever)
@survey.save!
(or just @survey.save
if you don't want to see exceptions) (或者如果您不想看到异常,则仅
@survey.save
)
If you want to make it easier to access these as instance variables in your view you can assign any of them to a variable after you've created them, and the association will be maintained: 如果您想更轻松地在视图中将它们作为实例变量进行访问,则可以在创建变量后将它们中的任何一个分配给变量,并将维护关联:
@question = @survey.question
It's up to you. 由你决定。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.