1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

Fix inversable associations when they are self-referencing

Self-referencing associations have the foreign key in both the owner of
the association and the source. Because of that we need to check in both
before telling if an object matches or not the foreign key.
This commit is contained in:
Rafael Mendonça França 2020-11-11 20:20:41 +00:00
parent a750b0cf8f
commit 8338481070
No known key found for this signature in database
GPG key ID: FC23B6D0F1EEE948
3 changed files with 13 additions and 4 deletions

View file

@ -341,7 +341,8 @@ module ActiveRecord
def matches_foreign_key?(record)
if foreign_key_for?(record)
record.read_attribute(reflection.foreign_key) == owner.id
record.read_attribute(reflection.foreign_key) == owner.id ||
(foreign_key_for?(owner) && owner.read_attribute(reflection.foreign_key) == record.id)
else
owner.read_attribute(reflection.foreign_key) == record.id
end

View file

@ -325,7 +325,7 @@ class InverseHasOneTests < ActiveRecord::TestCase
end
class InverseHasManyTests < ActiveRecord::TestCase
fixtures :humans, :interests, :posts, :authors, :author_addresses
fixtures :humans, :interests, :posts, :authors, :author_addresses, :comments
def test_parent_instance_should_be_shared_with_every_child_on_find
human = humans(:gordon)
@ -586,6 +586,14 @@ class InverseHasManyTests < ActiveRecord::TestCase
assert_predicate Human.joins(:interests).includes(:interests).first.interests, :any?
end
end
def test_association_stuff
comment = comments(:greetings)
Comment.create!(parent: comment, post_id: comment.post_id, body: "New Comment")
comment.body = "OMG"
assert_equal comment.body, comment.children.first.parent.body
end
end
class InverseBelongsToTests < ActiveRecord::TestCase

View file

@ -20,8 +20,8 @@ class Comment < ActiveRecord::Base
belongs_to :first_post, foreign_key: :post_id
belongs_to :special_post_with_default_scope, foreign_key: :post_id
has_many :children, class_name: "Comment", foreign_key: :parent_id
belongs_to :parent, class_name: "Comment", counter_cache: :children_count
has_many :children, class_name: "Comment", foreign_key: :parent_id, inverse_of: :parent
belongs_to :parent, class_name: "Comment", counter_cache: :children_count, inverse_of: :children
enum label: [:default, :child]