Reputation: 2139
I am developing a rails app where users can post, must like facebook. I want to implement a notification systems that alerts users to new posts. However, I am having trouble on how to tell if a user has viewed posts or not. I am literally clueless.
I am using devise gem which gives me access to certain user stats (if this helps):
create_table "users", :force => true do |t|
t.string "email", :default => "", :null => false
t.string "encrypted_password", :default => "", :null => false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", :default => 0
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.string "confirmation_token"
t.datetime "confirmed_at"
t.datetime "confirmation_sent_at"
t.string "unconfirmed_email"
t.integer "failed_attempts", :default => 0
t.string "unlock_token"
t.datetime "locked_at"
t.string "authentication_token"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.string "username", :default => "", :null => false
t.integer "admin", :default => 0
end
And my post model:
create_table "posts", :force => true do |t|
t.integer "user_id"
t.text "content"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
How can I implement a system that knows if a user has seen a post or not?
Upvotes: 2
Views: 187
Reputation: 2013
simple aproach would be like that:
create a model called Seen
rails g model Seen post:references user:references
models/seen.rb
belongs_to :user
belongs_to :post
models/user.rb
has_many :seens
has_many :seen_posts, through: :seens, source: :post
models/post.rb
has_many :seens
has_many :seen_users, through: :seens, source: :user
and you can create a method something like that
models/post.rb
def seen_by?(user)
seen_user_ids.include?(user.id)
end
controllers/posts_controller.rb
def show
@post = Post.find(params[:id])
current_user.seen_posts << @post unless @post.seen_by?(current_user)
end
Upvotes: 3