Add likes to your Mongoid models
Posted by Cesidio Di Landa on 08 November 2012
We needed a way to add likes to stories for Minstrels. We started looking for gems that provide this functionality and we found tombell/mongoid-voteable, that does a little more by providing a voting system to mongoid models. So we decided to fork this gem and focus only on likes. Today we gave it back to the open source community.
Installation
add the gem to your Gemfile
gem 'mongoid-likeable'
Usage
Include the Mongoid::Likeable
module to the models you want to like.
class Story
include Mongoid::Document
include Mongoid::Likeable
# ...
end
You can like a story by simply using the like
method on the model.
@story = Story.first
@user = User.first
@story.like @user
@story.unlike @user
There is also a method to check if a user liked a model.
@story.liked? @user # true if the user has already liked this
Likes are stored in a field called likes
, so you can sort models by like count.
Note: if your users are not stored in a Mongo collection or the ID field is
not called _id
, you can still pass the ID in as the second parameter instead.
@story.like @user.id
@story.liked? @user.id