mirror of
https://github.com/rails/rails.git
synced 2022-11-09 12:12:34 -05:00
Avoid the same foreign_key
and counter_cache
associations on SillyReply
`topic` and `reply` belongs_to associations on `SillyReply` are defined with the same `foreign_key` (`parent_id`) and `counter_cache` (`replies_count`) columns. This would cause unintentional side-effect (e.g. saving `SillyReply` object would cause double increment `replies_count`), so it is better to avoid that side-effect.
This commit is contained in:
parent
e925cb4d85
commit
afea273960
3 changed files with 7 additions and 7 deletions
|
@ -827,6 +827,7 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase
|
|||
|
||||
silly = SillyReply.create(title: "gaga", content: "boo-boo")
|
||||
silly.reply = reply
|
||||
silly.save!
|
||||
|
||||
assert_equal 1, reply.reload[:replies_count]
|
||||
assert_equal 1, reply.replies.size
|
||||
|
|
|
@ -117,9 +117,8 @@ class CascadedEagerLoadingTest < ActiveRecord::TestCase
|
|||
end
|
||||
|
||||
def test_eager_association_loading_with_has_many_sti_and_subclasses
|
||||
silly = SillyReply.new(title: "gaga", content: "boo-boo", parent_id: 1)
|
||||
silly.parent_id = 1
|
||||
assert silly.save
|
||||
reply = Reply.new(title: "gaga", content: "boo-boo", parent_id: 1)
|
||||
assert reply.save
|
||||
|
||||
topics = Topic.all.merge!(includes: :replies, order: ["topics.id", "replies_topics.id"]).to_a
|
||||
assert_no_queries do
|
||||
|
|
|
@ -9,6 +9,10 @@ class Reply < Topic
|
|||
has_many :silly_unique_replies, dependent: :destroy, foreign_key: "parent_id"
|
||||
end
|
||||
|
||||
class SillyReply < Topic
|
||||
belongs_to :reply, foreign_key: "parent_id", counter_cache: :replies_count
|
||||
end
|
||||
|
||||
class UniqueReply < Reply
|
||||
belongs_to :topic, foreign_key: "parent_id", counter_cache: true
|
||||
validates_uniqueness_of :content, scope: "parent_id"
|
||||
|
@ -54,10 +58,6 @@ class WrongReply < Reply
|
|||
end
|
||||
end
|
||||
|
||||
class SillyReply < Reply
|
||||
belongs_to :reply, foreign_key: "parent_id", counter_cache: :replies_count
|
||||
end
|
||||
|
||||
module Web
|
||||
class Reply < Web::Topic
|
||||
belongs_to :topic, foreign_key: "parent_id", counter_cache: true, class_name: "Web::Topic"
|
||||
|
|
Loading…
Reference in a new issue