docbrown/app/models/profile_pin.rb
Jeremy Friesen be97f2fc07
Favoring dependent: :delete_all over :destroy (#15442)
* Favoring dependent: :delete_all over :destroy

The `dependent: :destroy` callback is slower than `dependent: :delete`
and `dependent: :delete_all`.  We need only favor the `dependent:
:destroy` when there's callbacks that happen.

In the case of :destroy, ActiveRecord instantiates each object and then
runs destroy.  Whereas in the case of :delete, ActiveRecord issues a SQL
command to delete the related files.

It is often "safer" to use :destroy, as it guarantees that you'll
instantiate the record and run it's callbacks.  But sometimes you have
to go with the speed of SQL.

This relates to #14140.  Note there is still more to consider, but given
that we're looking at moving from :destroy on all of an article's page
views to :delete, we might buy enough time in the callback.

* Removing redundancy of article destroy

Prior to this commit, `before_destroy_actions` called the `bust_cache`
method which in turn called `touch_actor_latest_article_updated_at` but
`bust_cache` did not pass the destroying parameter.  Then
`before_destroy_actions` immediately called
`touch_actor_latest_article_updated_at` with `destroying: true`.

With this change, we remove one of those duplicate calls.

* Fixing specs regarding relationships

* Fixing specs regarding relationships
2021-11-24 13:56:16 -05:00

24 lines
1 KiB
Ruby

# @note When we destroy the related article (via pinnable), it's using
# dependent: :delete for the relationship. That means no
# before/after destroy callbacks will be called on this object.
class ProfilePin < ApplicationRecord
belongs_to :pinnable, polymorphic: true
belongs_to :profile, polymorphic: true
validates :profile_id, presence: true
validates :profile_type, inclusion: { in: %w[User] } # Future could be organization, tag, etc.
validates :pinnable_id, presence: true, uniqueness: { scope: %i[profile_id profile_type pinnable_type] }
validates :pinnable_type, inclusion: { in: %w[Article] } # Future could be comments, etc.
validate :only_five_pins_per_profile, on: :create
validate :pinnable_belongs_to_profile
private
def only_five_pins_per_profile
errors.add(:base, "cannot have more than five total pinned posts") if profile.profile_pins.size > 4
end
def pinnable_belongs_to_profile
errors.add(:pinnable_id, "must have proper permissions for pin") if pinnable.user_id != profile_id
end
end