Ruby on rails rails中的嵌套模型创建
我正在玩Rails控制台,想知道为什么以下代码不起作用:Ruby on rails rails中的嵌套模型创建,ruby-on-rails,ruby,activerecord,ruby-on-rails-3.1,model,Ruby On Rails,Ruby,Activerecord,Ruby On Rails 3.1,Model,我正在玩Rails控制台,想知道为什么以下代码不起作用: Question.create(body: "Why this does not work?", answer_attributes: {body: "Some Answer"}) question.save 这很奇怪,因为当我这么做的时候: question = Question.new(body: "Why this does not work?", answer_attributes: {body: "Some Answer"}
Question.create(body: "Why this does not work?", answer_attributes: {body: "Some Answer"})
question.save
这很奇怪,因为当我这么做的时候:
question = Question.new(body: "Why this does not work?", answer_attributes: {body: "Some Answer"})
question.answer
我得到的东西看起来像这样:
=> #<Answer id: nil, body: "Some Answer", question_id: nil, created_at: nil, updated_at: nil>
class Question < ActiveRecord::Base
has_many :answers, :dependent => :destroy, :inverse_of :question
accepts_nested_attributes_for :answers
end
class Answer < ActiveRecord::Base
belongs_to :question
validates :question, :presence => true
end
我明白了:
=> false
question.errors
@messages={:"answer.question_id"=>["can't be blank"]}>
当我调用.errors时,我得到以下信息:
=> false
question.errors
@messages={:"answer.question_id"=>["can't be blank"]}>
这两个对象都是新的,所以问题对象没有id是很正常的
我知道我可以先创建一个问题,然后调用上面的update_属性来创建答案对象。。。或者简单地创建一个问题,然后调用答案
我的问题是。。。子模型有没有办法在创建时获取其父模型的id
哦,如果你想知道,我确实有一个验证,需要一个答案才能有一个问题id值
谢谢 使用
create
尊重批量分配,因此请确保将attr\u accessible:answer\u attributes
添加到问题
类中,或使用
Question.create({body: "Why this does not work?", answer_attributes: {body: "Some Answer"}},)
我认为您需要为使用
接受嵌套属性,以便允许为嵌套模型分配质量。请参阅api参考资料,以获得有关该主题的更多信息我终于找到了问题的答案
我需要输入以下代码:
:inverse_of => :question
因此,我的问题模型如下所示:
=> #<Answer id: nil, body: "Some Answer", question_id: nil, created_at: nil, updated_at: nil>
class Question < ActiveRecord::Base
has_many :answers, :dependent => :destroy, :inverse_of :question
accepts_nested_attributes_for :answers
end
class Answer < ActiveRecord::Base
belongs_to :question
validates :question, :presence => true
end
类问题:毁灭,:问题的相反
接受\u嵌套的\u属性\u用于:答案
终止
我的答案模型如下所示:
=> #<Answer id: nil, body: "Some Answer", question_id: nil, created_at: nil, updated_at: nil>
class Question < ActiveRecord::Base
has_many :answers, :dependent => :destroy, :inverse_of :question
accepts_nested_attributes_for :answers
end
class Answer < ActiveRecord::Base
belongs_to :question
validates :question, :presence => true
end
class-Answertrue
终止
你能发布你的问答课吗?