Displaying posts by specific user?

爱⌒轻易说出口 提交于 2019-12-24 22:18:57

问题


Here I have some code:

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

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"?


回答1:


You could do this:

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

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!).




回答2:


def show
    @posts = current_user.posts
end


来源:https://stackoverflow.com/questions/14528885/displaying-posts-by-specific-user

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!