在Rails中的帖子中添加“Like / Different”按钮(Adding a “Like/Unlike” button to a post in Rails)

编程入门 行业动态 更新时间:2024-10-23 15:23:44
在Rails中的帖子中添加“Like / Different”按钮(Adding a “Like/Unlike” button to a post in Rails)

该网站是一个简单的社区,每个用户创建帖子,用户可能“喜欢”他们或“不像”他们。

我有一个Post和一个Like模型。 目前,我正在通过post.likes.size列出所有帖子以及每个帖子的喜欢尺寸。 喜欢帖子的按钮也在工作。

我不知道该怎么做是如何根据情况,如果一个职位应该显示不同按钮或类似的(取决于如果current_user已经喜欢该职位)。

类似的模型非常简单:

User_id // current user Post_id // post to associate

提前致谢!

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!

最满意答案

您应该在用户模型中定义关联

如果它是ror 2. *在用户模型中添加方法。 它应该是这样的:

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

假设Like有字段user_id和post_id,当然还有视图

if current_user.already_likes?(@post) #add unlike button end

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

更多推荐

本文发布于:2023-08-07 05:02:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1461252.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:按钮   帖子   Rails   post   button

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!