Rails:如何访问新记录的嵌套关联的父模型? [英] Rails: How can I access the parent model of a new record's nested associations?
问题描述
假设我们有标准的Post&评论模型,Post有 accepts_nested_attributes_for:commments
和:autosave =>
Suppose we have the standard Post & Comment models, with Post having accepts_nested_attributes_for :commments
and :autosave => true
set.
我们可以创建一个新帖子以及一些新的评论,例如:
We can create a new post together with some new comments, e.g.:
@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'
However, I need to be able to distinguish from within Comment (e.g. from its before_save or validation functions) between
- 此评论未附加到信息(无效)
- 此评论附加到未保存的信息(有效)
- this comment is not attached to a post (which is invalid)
- this comment is attached to an unsaved post (which is valid)
不幸的是,只需调用 self.post
from注释不工作,因为根据上面的,它返回nil直到保存发生后。在回调当然,我不(不应该)访问@post,只有自己的
Unfortunately, merely calling self.post
from Comment doesn't work, because per above, it returns nil until after save happens. In a callback of course, I don't (and shouldn't) have access to @post, only to self of the comment in question.
那么:从嵌套关联模型的角度来看,我如何访问新记录的嵌套关联的父模型?
So: how can I access the parent model of a new record's nested associations, from the perspective of that nested association model?
(FWIW,我使用它的实际示例允许人们创建一个裸体评论,然后会自动创建一个post来包含它,如果没有一个。我已经简化了这个例子,所以它不是特定于我的代码在不相干的方式。)
(FWIW, the actual sample I'm using this with allows people to create a naked "comment" and will then automatically create a "post" to contain it if there isn't one already. I've simplified this example so it's not specific to my code in irrelevant ways.)
推荐答案
我认为很奇怪,Rails不让你这样做。
I think it is strange that Rails does not let you do this. It also affects validations in the child model.
有一个在Rails bug跟踪器中有很多讨论和解决方案的机票:
There's a ticket with much discussion and no resolution in the Rails bug tracker about this:
p>
And a proposed resolution:
基本上,交易是,嵌套属性代码不会在子记录中设置父关联。
Basically, the deal is, the nested attributes code doesn't set the parent association in the child record.
在我链接的第二张票中提到了一些解决方法。
There's some work-arounds mentioned in the second ticket I linked to.
这篇关于Rails:如何访问新记录的嵌套关联的父模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!