显示特定用户的帖子? [英] Displaying posts by specific user?

查看:81
本文介绍了显示特定用户的帖子?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里有一些代码:

def show
    @post = Post.find()
  end
end

用户模型具有has_many:posts,而发布模型具有belongs_to:用户。现在如何使show action仅显示登录用户的帖子。登录用户是 current_user?

the user model has has_many :posts and the post model has belongs_to :user. Now how can I make the show action only display posts by the user logged in. User logged in is "current_user"?

推荐答案

您可以这样做:

def show
  @post = Post.where(user_id: current_user.id)
end

但是变量存在小故障,您应该重命名 @ post @posts ,因为这将是多个Posts的数组(如果这样,也不要忘记在视图中更改变量! )。

But there is glitch with the variable, you should rename @post to @posts since this will be an array of several Posts (if so, don't forget to change the variable in your view too!).

这篇关于显示特定用户的帖子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆