我有类似的评价:
Evaluation.rb
has_one :cardio
has_one :neuro
Cardio.rb
belongs_to :evaluation
Neuro.rb
belongs_to :evaluation
我的评估控制器与此类似:
def create
@patient = Patient.find(params[:id])
@evaluator = Evaluator.find(session[:evaluator_id]) if session[:evaluator_id]
@evaluation = Evaliation.new(:patient_id => @patient.id, :evaluator_id => @evaluator.id)
@neuro = Neuro.new(:evaluation_id => @evaluation.id)
@cardio = Cardio.new(:evaluation_id => @evaluation.id)
if (@evaluation.save! && @neuro.save! && @cardio.save!)
redirect_to evaluation_path(@evaluation.id), :notice => "Evaluation created"
else
render ("new")
end
end
创建评估时,也会创建有氧运动和神经元,但是使用null evaluation_id。
我试图将@cardio = Cardio.new(:evaluation_id => @evaluation.id)
移到if
内,但它也没有用。
答案 0 :(得分:2)
@evaluation
将不会设置ID,因此在您创建@neuro
和@cardio
时,@ evaluation.id将为nil。换句话说:
@evaluation = ...
if (@evaluation.save!)
@neuro = Neuro.new(:evaluation_id => @evaluation.id)
@cardio = Cardio.new(:evaluation_id => @evaluation.id)
if (@neuro.save! && @cardio.save!)
redirect_to evaluation_path(@evaluation.id), :notice => "Evaluation created"
else
render ("new")
end
else
render ("new")
end