Instead of text comments, we can easily state our opinion on the article by clicking a ‘Like’ button or a ‘Vote’ arrow. It is not uncommon that this function plays a role of recommendation. Last week, I added a similar function called ‘Likeable’ to my blog-like app. Here is the key notes.
Migration and Models
First of all, we
rails g migration create_likes.
Here, like boolean will show the choice of like(true) or unlike(false), :user_id will show who made the choice.
t.references :likeable, polymorphic: true will generate two columns: _likeableid and _likeabletype (e.g. Post or Comment).
With Polymorphic association, a model can belong to more than one other model, on a single association 1. In our case, like model can belong to post model or comment model.
We would like to use a member routes here.
It will recognise ‘/post/post_id/like’ and ‘/post/post_id/comment/id/like’ with POST, route to the action of PostsController and CommentsController, create the like_post_path and like_post_comment_path helpers.
Here we specify the method POST instead of the default a_tag method GET, by adding
Now we need some actions.
Here, we will pass params of @post to likeable_id and likeable_type, current_user ‘s id and set ‘true’ on like boolean.
Every time we hit the ‘Thumbs-up’ button, it will hit the datebase and rebuild the whole page. It’s quite expensive. So we will use another rails magic here.
remote: true: ‘<%= link_to like_post_path(@post, like: true), method: ‘post’, remote: true do %>’. It will become a ajax request when we hit the ‘Thumbs-up’.
In the meantime, we add response to this request in controller, revise our show.html.erb and add a
like.js.erb view template file in app/views/posts, respectively.
We can also add a ‘Unlike’ function with a ‘Thumbs-down’ button.
like: true params, we set it to false. In order to show the total likes, we add a method called
total_likes in post.rb.