我正在创建一个应用,其中会员注册并可以创建帖子,用户可以在该帖子上撰写评论而无需注册,评论有自己的索引视图。我一直在搜索,但找不到如何只显示特定于他们的帖子的当前用户评论的答案。任何帮助将不胜感激。提前谢谢。
我有以下关联:
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语句并将其与评论相关联,以便只有帖子的所有者才能看到所有相关评论? < / p>
答案 0 :(得分:0)
假设您的评论模型有一列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