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:
parent
a750b0cf8f
commit
8338481070
3 changed files with 13 additions and 4 deletions
|
@ -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
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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]
|
||||
|
||||
|
|
Loading…
Reference in a new issue