按特定用户显示帖子?

时间:2013-01-25 19:20:01

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

我在这里有一些代码:

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

用户模型有has_many:posts,帖子模型有belongs_to:user。现在,我如何才能使show动作仅显示登录用户的帖子。登录的用户是“current_user”?

2 个答案:

答案 0 :(得分:1)

你可以这样做:

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

但是变量出现故障,您应该将@post重命名为@posts,因为这将是几个帖子的数组(如果是这样,请不要忘记更改您的变量)查看!)。

答案 1 :(得分:0)

def show
    @posts = current_user.posts
end