1

I have two models: Books and pages in a typical one_to_many relationship.

How can I make the following

page_path(@page)

output this path:

bookname/page/pageid

instead of

page/pageid

If I override the to_param, all I can do is make a path like localhost/page/bookid/pageid but that's not what I want.

Zuhaib Ali
  • 3,344
  • 3
  • 20
  • 32
  • possible duplicate of [How can I globally override a rails url helper?](http://stackoverflow.com/questions/28675193/how-can-i-globally-override-a-rails-url-helper) – lulalala Aug 12 '15 at 08:57

3 Answers3

2

Not sure if it's possible to get exactly what you want, but you can make the Page a nested resource under book like this:

resources :books do
  resources :pages
end

Then you will get:

localhost/book/bookid/page/pageid

Then you can override `to_param' to get:

localhost/book/bookid-bookname/page/pageid

Matt
  • 5,328
  • 2
  • 30
  • 43
  • if I do nesting, I'll have to use helpers like `books_pages_path(@book,@page)`. I need to use the plain `pages_path(@page)` helper. – Zuhaib Ali Nov 20 '12 at 16:18
1

I'm assuming you mean to have path as /:book_name/page/:id

In routes.rb:

match '/:book_name/page/:id' => "page#show", :as => :page

In the controller you would access params[:id] to get page.id and params[:book_name] to get the name of the book.

tw airball
  • 1,359
  • 11
  • 12
  • Routing is working pretty well. I'm exactly stuck over not being able to use the page_path helper to output this exact path. – Zuhaib Ali Nov 20 '12 at 16:16
  • no. with this definition in the routes.rb you'll have to provide book name as an argument to the page_path function like `page_path("Some Book Name",@page)` – Zuhaib Ali Nov 20 '12 at 16:35
0

I discovered that to have full control over path helpers, you have to override those inside the application_helper.erb file. The following code worked for me:

def pages_path(@page)
  @bookpath = Book.find(@page.book_id)
  @bookpath + '/page/' + @page.id
end

The helper only creates the path. You still need to link it to a particular action in routes.rb. You may even nest the pages resource inside the books resource. The only important thing is that the path generated by the above helper must be recognizable by the rails application.

Zuhaib Ali
  • 3,344
  • 3
  • 20
  • 32