i have simple module inquest with comments , I used noticed gem to add notifications to comments , but when I delete inquest post , it stops server with page not working , and delete the whole account , like I can't login with that account again.i'm new with this gem. inquest.rb
class Inquest < ApplicationRecord
acts_as_votable
belongs_to :user, dependent: :destroy
has_many :comments, -> {order(:created_at => :desc)}, dependent: :destroy
has_many_attached :images
validates :description, presence: true
has_noticed_notifications model_name: 'Notification'
has_many :notifications, through: :user, dependent: :destroy
validates :title, :presence => true, :length => {
:maximum => 250,
:minimum => 25,
:tokenizer => lambda { |str| str.scan(/\w /) },
:too_long => "Please limit your summary to %{count} words"
}
end
notification.rb
class Notification < ApplicationRecord
include Noticed::Model
belongs_to :recipient, polymorphic: true
end
comment.rb
class Comment < ApplicationRecord
belongs_to :inquest
belongs_to :user
validates :content, presence: true
after_create_commit :notify_recipient
before_destroy :cleanup_notifications
has_noticed_notifications model_name: 'Notification'
private
def notify_recipient
Commentnotification.with(comment: self, inquest: inquest).deliver_later(inquest.user)
end
def cleanup_notifications
notifications_as_comment.destroy_all
end
end
user.rb
has_many :notifications, as: :recipient
commentnotification.rb
def message
@inquest = Inquest.find(params[:comment][:inquest_id])
@comment = Comment.find(params[:comment][:id])
@user = User.find(@comment.user_id)
"#{@user.user_name} commented on #{@inquest.title.truncate(10)}"
end
def URL
inquest_path(Inquest.find(params[:comment][:inquest_id]))
end
CodePudding user response:
The issue is you have dependent: :destroy
in your association:
class Inquest < ApplicationRecord
belongs_to :user, dependent: :destroy
end
which deletes the user with Inquest
so the account is deleted. A User
can have many Inquest
and there are many related associations usually with User
so destroying it with other objects is a bad idea. Instead, the User
model should have dependent: :destroy
with the associations in general cases.