Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

mark_as_read! :all for associations #99

Closed
Frexuz opened this issue Mar 17, 2018 · 3 comments
Closed

mark_as_read! :all for associations #99

Frexuz opened this issue Mar 17, 2018 · 3 comments

Comments

@Frexuz
Copy link
Contributor

Frexuz commented Mar 17, 2018

class Conversation < ApplicationRecord
  has_many :messages, dependent: :destroy

  def read(user)
    # messages.unread_by(user).each { |message| message.mark_as_read! for: user }
    # or
    # messages.mark_as_read! :all, for: user
  end


class Message < ApplicationRecord
  acts_as_readable on: :created_at
  belongs_to :conversation, counter_cache: true
end

conversation.read(current_user)
  1. The first example works (messages.unread_by(user).each), but it creates 1 record per resource+user (with 2 users per conversation, this table will be twice as long as the messages table).
  2. mark_as_read! :all for associations doesn't seem to be supported, since it just <NULL>s the column in the database, to make the optimized version, and I can't know for which conversation I've read all messages. And therefore, the cleanup_read_marks also won't work ofc.

Is there a way around this? Or is it out-of-scope for this gem?

@ledermann
Copy link
Owner

Instead of handling Message as readable, you can use Conversation instead and touch the corresponding conversation if a message is added or updated. Consequence: Multiple new messages in one conversion will result in only one unread conversation.

Example:

class Conversation < ApplicationRecord
  acts_as_readable on: :updated_at

  has_many :messages, dependent: :destroy
end

class Message < ApplicationRecord
  belongs_to :conversation, counter_cache: true, touch: true
end

conversation = Conversation.last
conversation.mark_as_read! for: current_user

@Frexuz
Copy link
Contributor Author

Frexuz commented Mar 19, 2018

I was thinking that first, but then I can't get how many messages are read/unread :)

@Frexuz
Copy link
Contributor Author

Frexuz commented Mar 19, 2018

Or, maybe just query how many messages are created after the conversation's read timestamp? 🤔

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants