in Ruby on Rails

Routes, Controllers, and link_to

On my familybox project I wanted to allow people to look up all the posts from a specific individual. For some reason clicking on their name when listed next to a post would simply redirect you to /site/index even though I was calling link_to blog.user.username.

After some research on the amazing Stackoverflow site I realized my problem. First I needed to create a users_controller.rb file. This looked like:

Then I needed to add the following line to my routes.rb:

So that when I make a call to a user it would show that user’s page. That page will then list all their posts. This means I needed to create a /views/users/show.html.erb file which resulted in this:

After that I had to figure out how to make the correct call. The original link_to was still redirecting to /site/index. I realized that I needed to make a call to a different controller. I ended up with this in my /views/site/index.html.erb file.

With this line of code the display text is the blog (or post) owner’s name. Then we are saying we need to reach out to the users_controller.rb and make a call to the ‘show’ action. Show wants a parameter passed (the id number) so we send that with our call and voila! We now have pages that display individual users posts (or blogs or what have you).

Write a Comment

Comment