Few months ago, I added a ‘Like’ function to my rails project. It’s a lovely function, but has some problems left. One is that users could like a single post/comment as much as they can, the other one is that users are not able to unlike.
Thus, I tried to improve the likeable function this weekend. First thing I came up with my head was to add a uniqueness validation.
Here is the code I added in
It worked. ‘User’ could not cheat any more, well, up to a point. But if users want to their mind later on, they are not allowed to do so.
Regarding the second issue, I decided to handle it this way.
Let’s assume there is a user called Mr.R. R liked a post, the params[:like] set to true. We would like to provide a link so that R could send another POST with the params[:like] = false. If R haven’t make the choice or unliked it before, then a link to POST with the params[:like] = true is available.
First of all, I changed the like method in
Here, if R has already liked/unliked the post, and then changed his mind, we would update the
like attribute rather than creating another data.
There are two methods in
application_controller, which are available to views and posts/comments controllers.
Then I adjusted
show.html.erbin the view. As discussed before, I provided the oppsite like/unlike button to users’ former dicision.
The comments like/unlike function is similar.
This improvement killed me a lot time this weekend, but thankfully, it worked at last. However, there must be a much easier & clean way to do it.
By the way, I had updated my app to bootstrap 3.2, a more resposive-friendly version. It was an nightmare to change the style, like css class/id name etc. I also used fontawesome icons instead of the old ones. The app looks just fine.