Reputation: 3384
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.
Upvotes: 1
Views: 600
Reputation: 3384
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.
Upvotes: 0
Reputation: 1359
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.
Upvotes: 1
Reputation: 5398
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
Upvotes: 2