我想初始化一个对象,但我不想创建对象到数据库,直到用户点击保存。我已经得到这个只与父对象一起工作,但我似乎无法让我的子对象关联到父对象,因为我还没有父对象的ID。我在下面的代码中做了什么错误?谢谢。如何在不保存父项的情况下在Rails中构建我的对象上的子对象?
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
如果不插入记录到数据库中,您无法“保留”标识。这就是自动递增数据库列的工作原理。 – max
@max,是的,我明白 - 我只是用这种方式解释它,试图传达我正在尝试做的事情。虽然看起来我做得不好。 – daveomcd