问题
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