ruby-on-rails - 如何在 Rails 中的对象上构建子关联而不保存父对象?

标签 ruby-on-rails ruby-on-rails-4 activerecord associations

我正在尝试初始化一个对象,但在用户单击“保存”之前我不想将对象创建到数据库中。我已经让它只与父对象一起使用,但我似乎无法让我的子对象与父对象关联,因为我还没有父对象的 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/

相关文章:

ruby-on-rails - 来自 Rails 4.2 图像缓存的特定图像将不会更新,无论我们尝试什么

ruby-on-rails - rails user_signed_in 的参数数量错误(2 对 1)?和当前用户

mysql - 在 rails 中使用特定的 mysql 索引

ruby-on-rails - 使用 ActiveRecord 在数据库中存储数组

ruby-on-rails - 使用部署在 Heroku 上的 Redmine 和 Integrity 在 GitHub 上的私有(private)仓库上跟踪 Rails 项目

ruby-on-rails - 数据库触发器与 Rails ActiveRecord 回调的优缺点?

ruby-on-rails - map(& :name) do in this Ruby code? 是什么意思

ruby-on-rails - 在 ruby​​ on rails 4.2.0 中隐藏记录而不是删除它们

javascript - 为 jquery 添加 Rails 输入名称时遇到问题

mysql - Active Record 第三层关系查询