Rails - Querying Noticed Notification with the params id

Viewed 28

I have searched through the related questions for example this one and the solutions marked there doesn't work for me.

So here is my problem:

I want to get a list of notifications that are for a specific recipient, and the notifications have to be made on comments belonging to a specific plant.

Currently I am using ruby to filter but the database hit is not ideal.

Here is the state of my code.

Models:

class Plant < ApplicationRecord
  has_many :comments
end

class User < ApplicationRecord
  has_many :notifications, as: :recipient, dependent: :destroy
end

class Notification < ApplicationRecord
  belongs_to :recipient, polymorphic: true
end

class Comment < ApplicationRecord
  has_noticed_notifications
end

class CommentNotification < Noticed::Base
  def comment
    params[:comment]
  end
end

This is the query I am currently using: @plant.comments.flat_map { |comment| comment.notifications_as_comment }.filter { |notification| notification.recipient == current_user }.map(&:mark_as_read!)

Any help is deeply appreciated...

1 Answers

I resolved this by making a comment method and then using that in my filter, it also killed all the excess dB hits I was getting.

  def comment_id
    self[:params][:comment].id
  end

Then I used this query to arrive at the result, looks cleaner too. Note comment_ids = @plant.comments.ids

Notification.unread.where(recipient_id: current_user.id)
      .filter { |notification| comment_ids.include?(notification.comment_id) }
      .map(&:mark_as_read!)
Related