views:

42

answers:

2

I'm interested in learning in Rails 3, how to grab the URL with something like params[:urlpath]

and then indexing it with /

so if I had a url like examples:

/books/1
/books/1/authors/3
/books/1/authors/3/chapters
/books/1/authors/3/chapters/33

I could always obtain 1

something like params[:urlpath] index[2]

I need this to populate the following which is happening on the page:

$.ajax({
    url: '/nav/sidenav',
    data: "urlpath=" + urlpath
});

ideas? thxs

+2  A: 

Add the following to your routes.rb:

match '/modelstuff/:id' => "controller#method"

Then you can use params[:id]

webdestroya
I'm making an AJAX call to get a sub navigation via /nav/sidenav and I need to know the current page's URL to know how to populate nav/sidenav properly, which is why params[:id] doesn't work in this situation but I believe I need the sidenav to determine the ID.. Thoughts?
WozPoz
@WozPoz - You should take a look at the [Rails Guide](http://guides.rubyonrails.org/routing.html#non-resourceful-routes) on Routing and requests
webdestroya
@webdestroya, thanks. any reason why?
WozPoz
@WozPoz - Because it provides info on various ways to do what you want.
webdestroya
ok added the AJAX call above to help clear out the use case. thanks guys
WozPoz
+1  A: 

If your URLs look like /books/1/authors/3/chapters/33

Then your routes should be:

resources :books do 
  resources :authors do
    resources :chapters
  end
end

This is called Nested Routes.

Then, in your controller:

/app/controllers/chapters_controller.rb

def show
  @book = Book.find(params[:book_id])
  @author = @book.authors.find(params[:author_id])
  @chapter = @author.chapters.find(params[:id])
end

Sort of magic.

Jesse Wolgamott
Very cool. But in the case mentioned above I'm not calling the chapters_controller. I'm calling app/controllers/navs
WozPoz
Jesse Wolgamott