You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Set a source association when setting a belongs_to association
When a through association that is a belongs_to association is set, we
don't set the source association, which might be confusing, because the
source association is available after saving and reloading the record.
For example:
class Post < ActiveRecord::Base
belongs_to :author
has_many :comments
end
class Comment < ActiveRecord::Base
belongs_to :post
has_one :post_author, through: :post
end
class Author < ActiveRecord::Base
has_many :posts
end
The post association in this case is a belongs_to association and also
it's used as a through association. Before this commit the result of
assigning the post to the comment would be the following:
comment = Comment.new(text: "Just a comment")
author = Author.new(name: "drogus")
post = Post.new(title: "A title", author: author)
comment.post = post
comment.post_author #=> nil
comment.save
comment.reload
comment.post_author #=> #<Author name: "drogus">
With a fix introduced in the commit, the post_author would be set before
saving the record:
comment = Comment.new(text: "Just a comment")
author = Author.new(name: "drogus")
post = Post.new(title: "A title", author: author)
comment.post = post
comment.post_author #=> #<Author name: "drogus">
comment.save
comment.reload
comment.post_author #=> #<Author name: "drogus">
0 commit comments