【发布时间】:2013-01-26 03:32:57
【问题描述】:
这里有一些代码:
def show
@post = Post.find()
end
end
用户模型有has_many :posts 并且帖子模型有belongs_to :user。现在如何使显示操作仅显示登录用户的帖子。登录用户是“current_user”?
【问题讨论】:
标签: ruby-on-rails ruby ruby-on-rails-3 devise
这里有一些代码:
def show
@post = Post.find()
end
end
用户模型有has_many :posts 并且帖子模型有belongs_to :user。现在如何使显示操作仅显示登录用户的帖子。登录用户是“current_user”?
【问题讨论】:
标签: ruby-on-rails ruby ruby-on-rails-3 devise
你可以这样做:
def show
@post = Post.where(user_id: current_user.id)
end
但是变量存在故障,您应该将@post 重命名为@posts,因为这将是一个包含多个帖子的数组(如果是这样,请不要忘记在您的视图中更改变量!)。
【讨论】:
def show
@posts = current_user.posts
end
【讨论】: