Show specific user blogs on rails

Well, I started to study the rails and, of course, I started writing a service with personal blogs (something like livejournal). I have scaffold posts and a custom model (thanks Devise). Now I'm trying to show all the messages of a specific user with something like / username / posts in the url, but I really can not figure out how to do this. Nested resources already created in routes

resources :users do resources :posts end 

and connected user and mail models using

 has_many :posts 

and

 belongs_to :user 

Should I create a controller for the user or not? Is there any suitable way for this?

PS Thanks for the answer. Trying to learn the rails, but almost every tutorial I found ends with scaffolding and that is not very useful.

Edit 1: Thanks to the idea of ​​a β€œmatch,” I solved half the problem. The other (unauthorized) half selects messages written by a specific user

Edit 2: Added

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

For the controller, but I have a "undefined method` posts' "error in the message controller.

+4
source share
2 answers

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

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

That way, you only request one user , and you can use .posts relashionship without errors.

+3
source

Using

 resources :users do resources :posts end 

you will get urls like '/ users / 1 / posts'

First, to have a 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 a match

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

which will lead you to the message controller and show the action.

+1
source

All Articles