Rails: How can I access the parent model of a new nested association record?

Suppose we have standard Post and Comment models, with Post having accepts_nested_attributes_for :commmentsand :autosave => true.

We can create a new post along with some new comments, for example:

@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 Comment (for example, from its before_save or validation functions) between

  • This comment is not attached to the message (which is not valid)
  • this comment is attached to an unsaved post (which is valid)

, self.post , , , nil , . , ( ) @post, , .

: ?

(FWIW, , , "", "", , . .)

+5
2

, Rails . .

Rails :

:

:

, , .

, , .

+5

, . , , - .

0

All Articles