我正在尝试初始化一个对象,但在用户单击“保存”之前我不想将对象创建到数据库中。我已经让它只与父对象一起使用,但我似乎无法让我的子对象与父对象关联,因为我还没有父对象的 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存在。
关于ruby-on-rails - 如何在 Rails 中的对象上构建子关联而不保存父对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33150008/