【发布时间】:2015-10-15 13:33:44
【问题描述】:
我正在尝试初始化一个对象,但我不想在用户单击保存之前将对象创建到数据库中。我已经让它只与父对象一起工作,但我似乎无法让我的子对象与父对象关联,因为我还没有父对象的 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
【问题讨论】:
-
您不能在不向数据库中插入记录的情况下“保留”ID。这就是自动递增数据库列的工作原理。
-
@max,是的,我明白了——我只是以这种方式解释它,试图传达我想要做的事情。虽然看起来我做得很糟糕。
标签: ruby-on-rails ruby-on-rails-4 activerecord associations