2016-09-15 133 views
0

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

我有以下的关联:

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语句在视图中陈述涉及,要审查,因此,只有职位的拥有者可以查看所有相关评论?

回答

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 
+0

我的问题是,评论家并不需要注册,所以数据库就不会创建审查用户的记录,我需要在其中一种方式我可以参考创建该帖子的用户以及属于该帖子的评论。因此,如果current_user是Post创建者,他需要能够查看为其帖子创建的所有评论。 –

相关问题