在创建操作上填充外键

时间:2011-09-26 00:48:05

标签: ruby-on-rails foreign-keys

我有类似的评价:

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内,但它也没有用。

1 个答案:

答案 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