I have a Evaluation similar to this:
Evaluation.rb
has_one :cardio
has_one :neuro
Cardio.rb
belongs_to :evaluation
Neuro.rb
belongs_to :evaluation
My evaluation controller is similar to this:
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
When the evaluation is created the cardio and neuro are created too, but with null evaluation_id.
I tried to move the @cardio = Cardio.new(:evaluation_id => @evaluation.id)
inside the if
but it didnt worked too.
@evaluation
won't have an id set until you save it, so @evaluation.id will be nil when you are creating @neuro
and @cardio
. In other words:
@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
精彩评论