【问题标题】:show reviews for current_user only using devise仅使用 devise 显示 current_user 的评论
【发布时间】:2016-09-15 07:54:25
【问题描述】:

我正在创建一个应用程序,其中成员注册并可以创建帖子,用户可以在该帖子上撰写评论而无需注册,评论有自己的索引视图。我四处搜索,但找不到关于如何仅显示特定于其帖子的当前用户评论的答案。任何帮助将不胜感激。提前致谢。

我有以下关联:

class User < ApplicationRecord
 has_many :posts
 has_many :reviews, through: :posts
end

class Post < ApplicationRecord
 belongs_to :user
end

class Review < ApplicationRecord
 belongs_to :post
end

在评论控制器索引方法中,我有以下代码运行良好,但它向所有用户显示评论,因为只有登录用户需要能够查看特定帖子的所有评论。

def index
 post = Post.friendly.find(params[:post_id])
 @reviews = post.reviews
end

是否可以在视图中使用 user_id 和 post_id 使用 if/else 语句并将其与评论相关联,以便只有帖子的所有者才能看到所有相关评论?

【问题讨论】:

    标签: ruby-on-rails devise ruby-on-rails-5


    【解决方案1】:

    假设您的评论模型有一个 created_by_id 列来存储创建该评论的用户 ID。

    这样试试

    def index
     post = Post.friendly.find(params[:post_id])
    
     #Write where condition to filter current_user reviews
     @reviews = post.reviews.where(created_by_id: current_user_id)
    end
    

    【讨论】:

    • 我的问题是审稿人不需要注册,所以数据库不会有创建评论的用户的记录,我需要一种可以引用用户的方法使用属于该帖子的评论创建帖子。因此,如果 current_user 是帖子创建者,他需要能够查看为他们的帖子创建的所有评论。
    猜你喜欢
    • 1970-01-01
    • 2015-07-13
    • 2020-08-29
    • 1970-01-01
    • 2011-10-02
    • 2020-12-11
    • 2013-06-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多