Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

very beginner RoR routing (new dynamic URL)

I have worked through the "getting started" Rails tutorial and am trying to understand routing better so that I can expand the sample project. (I've read this routing guide but didn't fully understand it - I think what I'm trying to do is simpler than what's covered there.)

Taking the sample blog project as a base, I am trying to add the ability to view all entries by a given author. I've modified the original project so that "author" is a field in the database and is accessible in the index (along with "title" and "text") (I can call @book.author), and I've figured out a (probably very hacky and incorrect) way of listing all authors and subjects on a separate page, but I have been unable to set up a way of filtering the articles by author.

In the same way that the "show" link in the sample project passes the article id to the controller and gives a view of the article with that id, I want to be able to have a similar link for each author which would pass the contents of the :author field to the controller to get all articles that share that author.

(I went down a really tangled rabbit hole manually setting up a separate controller for "authors" and trying to create a gets "authors/:author" line in the routes.rb file. Creating the controller and a view where I could list the authors themselves worked, but any attempt to set up a route with :author (or :id) as a parameter (so that each author would have a page listing his articles) didn't work - not sure why given that it looked, to me, the same as what was shown in the routing guide (above). But I'm pretty sure this is not the way to do this, so I'm starting over and trying to do it right.)

(I hope that this question isn't too general. I'm assuming that the answer here is very simple - I just haven't been able to figure it out from the obvious documentation or tutorials I've seen.)

like image 659
user3092118 Avatar asked Nov 22 '25 00:11

user3092118


1 Answers

It's usually a simple nested resources...

resources :authors do
  resources :articles 
end

This gives you a route authors/:author_id/articles (named as author_articles_path(@author))

In your articles index controller you would do..

def index
  @author = Author.find(param[:author_id])
  @articles = @author.articles
end

hope this helps.

like image 106
SteveTurczyn Avatar answered Nov 23 '25 14:11

SteveTurczyn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!