添加“喜欢/不喜欢"按钮到 Rails 中的帖子 [英] Adding a "Like/Unlike" button to a post in Rails
问题描述
该网站是一个简单的社区,每个用户都在其中创建帖子,用户可以喜欢"或不喜欢"他们.
The site is a simple community where each user creates posts and users may "like" them or "unlike" them.
我有一个 Post 和一个 Like 模型.目前,我通过 post.likes.size 列出所有帖子以及每个帖子的喜欢大小.喜欢帖子的按钮也可以使用.
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.
我不知道该怎么做取决于具体情况,如果帖子应该显示不同按钮或类似按钮(取决于 current_user 是否已经喜欢该帖子).
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).
like 模型很简单:
The like model is very simple:
User_id // current user
Post_id // post to associate
提前致谢!
推荐答案
你应该在用户模型中定义关联
You should define association in user model
如果是 2.* 在 User 模型中添加方法.它应该是这样的:
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
假设 Like 有字段 user_id 和 post_id当然在视图中
Assuming Like has fields user_id and post_id and of course in view
if current_user.already_likes?(@post)
#add unlike button
end
这篇关于添加“喜欢/不喜欢"按钮到 Rails 中的帖子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!