The site is a simple community in which each user creates messages, and users can "like" them or "distinguish" them.
I have a Post and Like model. I am currently listing all posts, as well as the size of similar posts for each post via post.likes.size. A button to like the message also works.
What I don’t know how to do is how it depends on the case if the column should show a different button or something similar (depending on whether current_user likes this post).
A similar model is very simple:
User_id // current user Post_id // post to associate
Thanks in advance!
2. * add . :
has_many :likes def already_likes?(post) self.likes.find(:all, :conditions => ['post_id = ?', post.id]).size > 0 end
, user_id post_id , ,
if current_user.already_likes?(@post) #add unlike button end
, user_id post_id. , "unlike", b/c, , "". ( ), "".
nil, "" , , "" .
def user_likes(current_user, post_id) likes.find(:first, :conditions => ['user_id = ? AND post_id = ?', current_user, post_id] ).nil? end
, :
if user_likes(1, 12).nil? # show like button else #show unlike button end
Like :
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
.
def unlike # get the post #code to decrement the like counter of a specific post end
then from your view, create a button or link pointing to this action.
Source: https://habr.com/ru/post/1769021/More articles:MySQL Исчерпает 1.5 ТБ дискового пространства во время сортировки - mysqlBiztalk - can I create rules / policies programmatically? - biztalkNinject and redirected types (as is known in Castle Windsor) - ninjectHow to programmatically schedule a task to start when Windows shuts down? - c ++using native html vs css elements - htmlHow to insert values into MYSQL table using Select-Statementments - sqlDesigning real-time video for wxWidgets - c ++Detecting / tracking objects in Java - javaSVN: exporting empty directories - svnHow to dry my jQuery code and make it more readable / maintanable? - javascriptAll Articles