2015-10-15 50 views
0

我想初始化一个对象,但我不想创建对象到数据库,直到用户点击保存。我已经得到这个只与父对象一起工作,但我似乎无法让我的子对象关联到父对象,因为我还没有父对象的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 
+0

如果不插入记录到数据库中,您无法“保留”标识。这就是自动递增数据库列的工作原理。 – max

+0

@max,是的,我明白 - 我只是用这种方式解释它,试图传达我正在尝试做的事情。虽然看起来我做得不好。 – daveomcd

回答

2

评估的模型是不是很清楚,我,但基本上,如果你这样做

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

将添加对象的评价,不保存,不会要求report.id到在添加的时刻存在。

+0

我试过这种方式,但是当我在赋值后做了一个'@ report.evaluations.count'时,它仍然返回零。并且模型评估是报告的有效性,评估属于技能。 – daveomcd

+1

#count操作与数据库一起工作,有效地映射到select count(*)SQL操作。它将返回0,因为关联尚未保存。尝试使用#size或#length代替 –

+0

ohhh gotcha谢谢!感谢你的回答。我可以看到它已经填充,但它并没有显示在我的页面视图中,因为我猜测是由于我使用了“where”处理你已经提到过的相同情况,因为它不会工作,因为它是不是真的在数据库中。所以我现在要研究如何在我的评估中过滤这些记录。再次感谢! – daveomcd

相关问题