Show certain user's blog posts in rails

2019-06-24 06:44发布

问题:

Well, started to learn rails and of course started by writing a service with personal blogs (something like livejournal). I have posts scaffold and user model (thanks to Devise). Now I'm trying to show all posts by certain user with something like /username/posts in url but really can't understand how to make this rails-way. Already made nested resources in routes

resources :users do 
  resources :posts 
end

and connected user and post models with

has_many :posts

and

belongs_to :user

Should I create controller for user or not? Is there any proper way for this?

P.S. Thanks for the answer. Trying to study rails but almost every tutorial I found ends with scaffolding and that's not very helpful.

Edit 1: Thanks to the "match" idea I solved half of the problem. The other (unsolved) half is selecting posts written by certain user

Edit 2: Added

@user = User.where(:username => params[:username])
@posts = @user.posts

To controller, but I have "undefined method `posts'" error in posts controller.

回答1:

When you use where you get an array of objects from the query, not a single object.
And because of this you don't have the posts method on your @user variable.
Maybe you should change to something like this, to retrieve only one user:

@user = User.find_by_username(params[:username])

This way you have only one user queried and you can use the .posts relashionship without errors.



回答2:

When using

resources :users do
   resources :posts 
end

you will end up having urls like '/users/1/posts'

First to have username in case of id you need to write

def to_param
  self.username 
end

in your user model.

Or if you don't want your url to be /users/:id/posts you can create a route url using match

match ':username/posts' ,'posts#show' 

which will take you to the posts controller and show action.