简体   繁体   English

如何在 rails 中包含当前用户是否喜欢某个帖子?

[英]How to include if a post was liked by the current user in rails?

So I have a query with gets all the recent posts所以我有一个查询,获取所有最近的帖子

posts = Post.where(public: true).limit(25).order(created_at: :desc)

which returns the posts that I need.它返回我需要的帖子。 now I want to return the post but I also want to include if the user who is making the call has liked the post.现在我想返回帖子,但我也想包括拨打电话的用户是否喜欢该帖子。

I have a like table that just has the post_id, and user_id.我有一个只有 post_id 和 user_id 的类似表。

right now the way I have it is现在我的方式是

render :json => posts.as_json(:include => [:likes])

which returns all the people who have liked the post which is not what I want:它返回所有喜欢该帖子的人,这不是我想要的:

{
    "id": 43,
    "title": "asdfasdfs",
    "story": "adfaf sdf sd asdf sdf asdf saf adf",
    "created_at": "2017-05-10T22:40:54.587Z",
    "updated_at": "2017-05-10T23:18:47.653Z",
    "user_id": 8,
    "likes": [
      {
        "id": 1,
        "user_id": 4,
        "post_id": 43
      },
      {
        "id": 2,
        "user_id": 6,
        "post_id": 43
      }
    ]
  }

I either want to just include the like that is by the user (somehow having a wherein the include to limit it)我要么只想包含用户的类似内容(不知何故有一个其中包含来限制它)

or to somehow just make it a variable in the JSON called liked_by_me set to true or false.或者以某种方式使其成为名为like_by_me 的JSON 中的变量,设置为true 或false。 I am trying to avoid though having to do a map by hand and doing another 25 more queries, one for each post to see if it was liked by someone.我试图避免手动绘制地图并再做 25 个查询,每个帖子一个查询,看看它是否被某人喜欢。 What's the best way to do this?做到这一点的最佳方法是什么?

Thanks谢谢

You should query the many-to-many table with the current user's id and the post id, and if that record exists, this means that the user liked that post.您应该使用当前用户的 id 和帖子 id 查询多对多表,如果该记录存​​在,则表示该用户喜欢该帖子。 Store the like similar to how you stored the posts, but adding where clauses for the user id and the post id.存储类似于您存储帖子的方式,但为用户 ID 和帖子 ID 添加 where 子句。 If the row exists, it returns the row, if not, it will return nil.如果该行存在,则返回该行,如果不存在,则返回 nil。

I had similar 'problem' (instead of posts I had articles but it doesn't matter).我有类似的“问题”(而不是我有文章的帖子,但没关系)。 The way I choose to deal with this is as follows:我选择的处理方式如下:

User model looks like this:用户模型如下所示:

class User < ActiveRecord::Base
  has_many :articles ,dependent: :destroy 
  has_secure_password
  has_many :likes 
end

Article model:文章型号:

class Article < ActiveRecord::Base
    belongs_to :user
    has_many :likes
end

and the Like model :和 Like 模型:

class Like < ActiveRecord::Base
  belongs_to :article
  belongs_to :user
end

Likes controller should looks like :喜欢控制器应该看起来像:

def create
  @like=Like.new(article_id:params[:article_id],user_id:params[:user_id])

  if !(Like.find_by(user_id: params[:user_id], article_id: params[:article_id]))
     if current_user!=Article.find(params[:article_id]).user
       if @like.save
         flash[:success]='Thanks for your like'
         redirect_to article_path(params[:article_id])
       else
         render 'new'
       end
     else
       flash[:warning]="You can't like your article"
       redirect_to article_path(params[:article_id])
     end
  else
     flash[:danger]='You liked this article once'
     redirect_to article_path(params[:article_id])      
  end
end

Code for current_user : current_user 的代码:

  def current_user
    @current_user ||=User.find(session[:user_id]) if session[:user_id]
  end

In articles show template I've rendered the partial template named '_likes'在文章显示模板中,我呈现了名为“_likes”的部分模板

<%= render 'likes' %>

and I think what you are asking about is shown in these lines from partial template '_likes'我认为您要问的内容显示在部分模板“_likes”的这些行中

  <% if !Like.find_by(user_id: current_user, article_id:@article.id) %>
    <img src="/assets/no_like.png">
  <% else %>
    <img src="/assets/like.png">
  <% end %>

If you are logged in and you haven't yet liked an article the show template would look like : Article with no like from the user logged in如果您已登录但尚未点赞某篇文章,则显示模板将如下所示:登录用户没有点赞的文章

Another case : If you are logged in and you've liked the article the show template would looke like : Article with like from you另一种情况:如果您已登录并且喜欢该文章,则显示模板将如下所示:带有您喜欢的文章

I hope this will help you.我希望这能帮到您。

class User < ActiveRecord::Base
  has_many :articles ,dependent: :destroy 
  has_secure_password
  has_many :likes 
end
class Article < ActiveRecord::Base
    belongs_to :user
    has_many :likes

    def liked?(user)
      !!self.likes.find{|like| like.user_id==user.id}
    end

end
class Like < ActiveRecord::Base
  validates :user_id, uniqueness: { scope: [:article_id]}
  belongs_to :article
  belongs_to :user
end

Then you check:然后你检查:

if @article.liked?(@current_user)

Reference: https://medium.com/swlh/how-to-add-a-simple-like-button-to-your-rails-6-application-c1040999dc2参考: https : //medium.com/swlh/how-to-add-a-simple-like-button-to-your-rails-6-application-c1040999dc2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何计算“喜欢”计数并显示当前用户是否喜欢 SQL 中的这篇文章? - How to calculate 'Like' count and show if current user had liked this post in SQL? 如何使用 SQL 查询检索所有帖子并验证用户是否喜欢该帖子 - How to retrieve all post and verify if user liked the post with an SQL query MYSQL 如果用户喜欢某个状态,则将其包含在查询结果中 - MYSQL if a status is liked by a user include it in query results 获取所有帖子并发布用户喜欢 MySQL - get ALL posts AND post the user liked MySQL 获取主题的帖子,如果询问的用户喜欢该帖子,则获取0或1 - Get posts of a thread and 0 or 1 if the user asking liked the post 使用 sql 判断用户是否点赞了一个帖子 - Using sql to determine if the user has liked a post 查询以选择帖子并标记其中某些帖子是否被当前用户喜欢 - Query to select posts and mark if some of them liked by current user SQL / PHP-检查用户是否已经喜欢发布,是否与发布不同? - SQL/PHP - Check if user already liked post and if yes unlike? 多对多关系,以确定用户是否喜欢帖子 - Many-to-many relationship to determine if user has liked a post 计算产品被喜欢的次数以及特定用户在PHP和SQL中喜欢的所有产品 - Count how many times product is liked and all the products a particular user has liked in PHP and SQL
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM