如何在 Rails 中的对象上建立子关联而不保存父关联?

How can I build out child associations on my object in Rails without saving the parent?

我正在尝试初始化一个对象,但我不想在用户单击“保存”之前将对象创建到数据库中。我已经让它只与父对象一起工作,但我似乎无法让我的子对象与父对象关联,因为我还没有父对象的 id。我在下面的代码中做错了什么?谢谢

  def new

    # Build a new report object with the default type of "draft" and assign it to the player
    report_options = { player_id: @player.id,
                       author_id: current_user.id,
                        position: @player.position,
                            type: "draft",
                       submitted: false }

    @report = Report.new(report_options)

    @skills.where('disabled = (?)',FALSE).each do |skill|
      # On the line below I get an evaluation record with a proper skill id,
      # but report_id is `nil` because I'm guessing the report hasn't been 
      # created yet.  Is there a way to reserve an id for it without actually
      # committing the record to the database until the user saves the record?
      @report.evaluations.build(skill_id: skill.id)
    end

  end

我不太清楚评估模型,但基本上如果你做类似

@report.evaluations.build
@skills.where('disabled = (?)', FALSE).each do |skill|
  @report.evaluations << Evaluation.new(skill_id: skill.id)
end

它将在不保存的情况下将对象添加到评估中,并且不需要 report.id 在添加时存在。