我有什么:
scaffold Post title body user_id
scaffold Comment body tag post:references
post has_many :comments
当前评论 Controller :
def index
@comments = Comment.where(tag: [1, 3])
end
我想让当前的设计用户只看到他的所有帖子的评论列表。如何做呢?与 current_user
有关吗?
最佳答案
你可以直接在 User
模型上设置一个 has_many :through
关系假设你已经定义了一个 has_many :posts
关系并且适当的Post
和 Comment
的关系。例如,
class User < ActiveRecord::Base
has_many :posts
has_many :comments, through: :posts
end
class Post < ActiveRecord::Base
belongs_to :user
has_many :comments
end
class Comment < ActiveRecord::Base
belongs_to :post
end
现在,由于 devise
为您提供 current_user
,因此获取用户的评论很简单
def index
@comments = current_user.comments
end
def show
@comment = current_user.comments.find(params[:id])
end
希望这对您有所帮助。干杯。
关于ruby-on-rails - 当前用户只能看到对其帖子的评论,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35672942/