views:

56

answers:

4

Hi,

The site is a simple community where each user creates posts and users may "like" them or "unlike" them.

I have a Post and a Like model. Currently, I'm listing all posts and also the likes size for each post through post.likes.size . The button to like a post is also working.

What i don't know how to do is how to depending on the case, if a post should show the unlike button or the like (depending if the current_user already liked that post).

The like model is very simple:

User_id // current user
Post_id // post to associate

Thanks in advance!

A: 

create an action like this in your posts controller.

def unlike
   # get the post
   #code to decrement the like counter of a specific post
end

then from your view, create a button or a link that points to this action.

lakshmanan
I know that, but before showing the unlike button how do i know if I already liked it?
Martin
A: 

You should define association in user model

if it's ror 2.* add method in User model. it should look like this:

has_many :likes
def already_likes?(post)
  self.likes.find(:all, :conditions => ['post_id = ?', post.id]).size > 0
end

Assuming Like has fields user_id and post_id and of course in view

if current_user.already_likes?(@post)
  #add unlike button
end
Tadas Tamosauskas
A: 

You want to search for a record that matches the user_id and post_id. If you find one, you want to show the 'unlike' button, b/c that means the user has 'liked' the post already. If you don't (it returns nil), you want to show the 'like' button.

The following method returns nil if the user hasn't 'liked' the post, and not nil if the user has 'liked' the post.

def user_likes(current_user, post_id)
  likes.find(:first, :conditions => ['user_id = ? AND post_id = ?', current_user, post_id] ).nil?
end

So you can say:

if user_likes(1, 12).nil?
  # show like button
else
  #show unlike button
end
99miles
A: 

Also you could add validation to your Like model like so:

validate :user_does_not_already_like_post

def user_does_not_already_like_post
  errors.add(:user, "You can only like a post once.") if user.already_likes?(post)
end
Erik