0

I'm currently learning RoR and this might be a simple question, but I don't know how to do it. I've just created a simple blog, following a tutorial, but I want to add a liking system, so that users can like(like on Youtube or Facebook) a certain blog post. How would I do that?

Here's what I've been thinking about: Add a new column to my database called "Likes" of type integer, put a Like button in my views. Add a method in my controller that would add 1 whenever someone clicked it. I'm not really sure if that's the way to do it, as I'm completely new to Ruby and Rails.

Buno
  • 87
  • 7
  • 1
    Welcome to SO. Please provide more details to help us understand what exactly your problem is. For instance, start by sharing the relevant code and where specifically you're having trouble. – Leo Brito Jan 23 '16 at 16:36
  • Hey, I still haven't started building the thing itself. I'm just asking for advice about where I should start doing it. As I'm completely new to it, I'm not sure if that's the most effective way to do it. – Buno Jan 23 '16 at 16:46
  • Stack Overflow is a little "advice" and a lot "help debug problems in my code". We expect you to have tried, a lot, and then to ask, explaining what you tried along the way, why it didn't work, then supply a minimal example of what you tried along with supporting data and expected output. As is, we can't tell what you tried, whether you tried, what happened when you tried, resulting in a very broad question because we have no idea where you are in your learning curve, which would result in our writing tutorials explaining what to do. Please read "[ask]". – the Tin Man Jan 23 '16 at 22:22

1 Answers1

5

The fast and simple solution

Use this gem to get you going quickly.

The long one, if you plan on implementing your own solution from scratch

Say you have a Post model that can be liked by a User model, So when the user likes a post we want to keep track of that in new model / table which we will name Like. This Like model will belong to to both the User and Post

The models
class Post < ActiveRecord::Base
  has_many :likes

  # like the post
  def like(user)
    likes << Like.new(user: user)
  end

  # unlike the post
  def unlike(user)
    likes.where(user_id: user.id).first.destroy
  end
end

class User < ActiveRecord::Base
  has_many :likes
end

class Like < ActiveRecord::Base
  belongs_to :post
  belongs_to :user
  ## We make sure that one user can only have one like per post
  validates :user_id, uniqueness: {scope: :post_id}
end

#likes table attributes
id
user_id
post_id
How a user can like a post?
$rails console
> post = Post.first
> user = User.first
> post.like(user)
> post.likes.count #=> 1
> post.unlike(user)
> post.likes.count #=> 0
mtkcs
  • 1,696
  • 14
  • 27