显示特定用户的post?
这里我有一些代码:
def show @post = Post.find() end end
用户模型有has_many:posts,post模型有belongs_to:user。 现在,我如何才能使show动作仅显示用户登录的post。登录的用户是“current_user”?
你可以这样做:
def show @post = Post.where(user_id: current_user.id) end
但是变量存在故障,你应该将@post
重命名为@posts
因为这将是几个post的数组(如果是这样,不要忘记在视图中更改变量!)。
def show @posts = current_user.posts end