【问题标题】:How can I build out child associations on my object in Rails without saving the parent?如何在 Rails 中的对象上建立子关联而不保存父对象?
【发布时间】: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


【解决方案1】:

评估模型对我来说不是很清楚,但基本上如果你做类似的事情

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

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

【讨论】:

  • 我尝试过这种方式,但是当我在分配后执行@report.evaluations.count 时,它仍然返回零。而模型评估是一个has_many的Report,而Evaluation属于_一种技能。
  • #count 操作适用于数据库,有效地映射到 select count(*) SQL 操作。它将返回 0,因为关联尚未保存。尝试改用#size 或#length
  • 哦,谢谢!感谢你的回答。我可以看到它已被填充,但它没有显示在我的页面视图中,因为我猜是因为我使用了 where,在其中我正在处理您已经提到的相同情况,即 where 无法正常工作不在数据库中。所以我现在要研究如何在我的评估中过滤这些记录。再次感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多