【发布时间】:2009-12-13 09:36:01
【问题描述】:
假设我们有标准的 Post & Comment 模型,Post 具有 accepts_nested_attributes_for :commments 和 :autosave => true 集。
我们可以与一些新的 cmets 一起创建一个新帖子,例如:
@post = Post.new :subject => 'foo'
@post.comments.build :text => 'bar'
@post.comments.first # returns the new comment 'bar'
@post.comments.first.post # returns nil :(
@post.save # saves both post and comments simultaneously, in a transaction etc
@post.comments.first # returns the comment 'bar'
@post.comments.first.post # returns the post 'foo'
但是,我需要能够从 Comment 内部(例如,从其 before_save 或验证函数)中区分
- 此评论未附加到帖子(无效)
- 此评论附加到一个未保存帖子(有效)
不幸的是,仅从 Comment 中调用 self.post 是行不通的,因为根据上述,它在保存发生之前返回 nil。当然,在回调中,我没有(也不应该)访问@post,只能访问相关评论的自我。
那么:从嵌套关联模型的角度来看,我如何访问新记录的嵌套关联的父模型?
(FWIW,我使用它的实际示例允许人们创建一个赤裸裸的“评论”,然后会自动创建一个“帖子”来包含它,如果还没有的话。我已经简化了这个例子所以它不是以不相关的方式特定于我的代码。)
【问题讨论】:
标签: ruby-on-rails associations callback