扶手:我如何才能访问新记录的嵌套协会父模型? [英] Rails: How can I access the parent model of a new record's nested associations?
问题描述
假设我们有标准的邮政和放大器; Comment模型,具有邮政 accepts_nested_attributes_for:commments
和:自动保存=>真正
设置。
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'
不过,我需要能够从评论中的区别(例如从before_save或验证功能)
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
从评论不起作用,因为按照上面,它返回零,直到保存后发生。当然,在一个回调,我不(也不应该)访问@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,我用这与实际样品让人们创建一个赤裸裸的注释,然后会自动创建一个后遏制它,如果没有一个了。我已经简化这个例子所以它不是特定于无关紧要的方面我的code)
(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:
<一个href=\"https://rails.lighthouseapp.com/projects/8994/tickets/1943-nested-attributes-validations-circular-dependency\"相对=nofollow>嵌套属性验证
圆
依赖
和建议解决办法:
<一个href=\"https://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/2815-nested-models-build-should-directly-assign-the-parent\"相对=nofollow>嵌套模型:构建应该直接
分配
家长
基本上,交易是,嵌套的属性code不设置子记录的家长会。
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.
这篇关于扶手:我如何才能访问新记录的嵌套协会父模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!