Handle unread records and mark them as read with Ruby on Rails
Handle unread records and mark them as read with Ruby on Rails
Ruby gem to manage read/unread status of ActiveRecord objects - and it's fast.
https://github.com/ledermann/unread/releases
Step 1: Add this to your Gemfile:
gem 'unread'and run
bundleStep 2: Generate and run the migration:
rails g unread:migration
rake db:migrateIf you upgrade from an older release of this gem, you should read the upgrade notes.
…class Document {20=>{:unread=>1, :total=>10}, 82=>{:unread=>0, :total=>4}Using with_read_marks_for here is the key. It uses just one query and makes sure that the following unread? invocations use the result of the first query.
The main idea of this gem is to manage a list of read items for every reader after a certain timestamp.
The gem defines a scope doing a LEFT JOIN to this list, so your app can get the unread items in a performant manner. Of course, other scopes can be combined.
It will be ensured that the list of read items will not grow up too much:
Overall, this gem can be used for large data. Please have a look at the generated SQL queries, here is an example:
# Assuming we have a user who has marked all messages as read on 2010-10-20 08:50
current_user = User.find(42)
# Get the unread messages for this user
Message.unread_by(current_user)Generated query:
SELECT messages.*
FROM messages
LEFT JOIN read_marks ON read_marks.readable_type = "Message"
AND read_marks.readable_id = messages.id
AND read_marks.reader_id = 42
AND read_marks.reader_type = 'User'
AND read_marks.timestamp >= messages.created_at
WHERE read_marks.id IS NULL
AND messages.created_at > '2010-10-20 08:50:00'Hint: You should add a database index on messages.created_at.
Copyright (c) 2010-2023 Georg Ledermann and contributors, released under the MIT license
No open issues yet, or sync has not completed.