Skip to content

Commit

Permalink
Add counter_cache to the activity_object belongs_to association in th…
Browse files Browse the repository at this point in the history
…e notification model

Rails/SkipsModelValidations: Avoid using increment! because it skips
validations.
  • Loading branch information
acmetech committed Jan 17, 2017
1 parent 226f779 commit 259f6d7
Show file tree
Hide file tree
Showing 4 changed files with 5 additions and 22 deletions.
5 changes: 0 additions & 5 deletions app/models/socializer/activity_object.rb
Original file line number Diff line number Diff line change
Expand Up @@ -125,11 +125,6 @@ def liked_by
people
end

# Increments the unread_notifications_count by 1 and saves the record
def increment_unread_notifications_count
increment!(:unread_notifications_count)
end

# Reset unread_notifications_count to 0
def reset_unread_notifications
update!(unread_notifications_count: 0) if unread_notifications_count > 0
Expand Down
5 changes: 2 additions & 3 deletions app/models/socializer/notification.rb
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ class Notification < ApplicationRecord

# Relationships
belongs_to :activity, inverse_of: :notifications
belongs_to :activity_object, inverse_of: :notifications # Person, Group, ...
belongs_to :activity_object, inverse_of: :notifications,
counter_cache: :unread_notifications_count

# Validations
validates :activity_id, presence: true
Expand All @@ -23,8 +24,6 @@ class Notification < ApplicationRecord
scope :newest_first, -> { order(created_at: :desc) }

# Callbacks
# Increment the number of unread notifications
after_commit { activity_object.increment_unread_notifications_count }

# Class methods - Public

Expand Down
13 changes: 0 additions & 13 deletions spec/models/socializer/activity_object_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -135,19 +135,6 @@ module Socializer
end
end

context "#increment_unread_notifications_count" do
let(:activity_object) do
create(:activity_object)
end

before do
activity_object.increment_unread_notifications_count
activity_object.reload
end

it { expect(activity_object.unread_notifications_count).to eq(1) }
end

context "#reset_unread_notifications" do
let(:activity_object) do
create(:activity_object, unread_notifications_count: 10)
Expand Down
4 changes: 3 additions & 1 deletion spec/models/socializer/notification_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,9 @@ module Socializer
it { is_expected.to belong_to(:activity).inverse_of(:notifications) }

it do
is_expected.to belong_to(:activity_object).inverse_of(:notifications)
is_expected.to belong_to(:activity_object)
.inverse_of(:notifications)
.counter_cache(:unread_notifications_count)
end
end

Expand Down

0 comments on commit 259f6d7

Please sign in to comment.