2007/08/23

Rails Restful routing

Just now I tried to write some some restful application using rails, then I found there is some thing wront with Rails' routing.

In my application , there were three models: book , person and library, a person or library may have many books, but the book can only have one owner----person or library.

After setup other relationships in the models, I wrote this in the route.rb:

map.resources :books,
:path_prefix => '/person/:person_id',
:name_prefix => 'person_'

map.resources :books,
:path_prefix => '/library/:library_id',
:name_prefix => 'library_'
And in the controller , I done something like this:
if params[:person_id]
........
elsif params[:library_id]
.......
end

That worked well.

But I felt that either person or library was the book's owner, so I refactor the routing to this one for cleaning the url:
map.resources :books,
:path_prefix => '/owner/:person_id',
:name_prefix => 'person_'

map.resources :books,
:path_prefix => '/owner/:library_id',
:name_prefix => 'library_'
Controllers changed nothing, then something wrong still.
It's impossible to pass the "params[:library_id]" using any of the helper the methods like "library_new_book, library_...." etc.
In the development.log , I found Parameters from the "library" name-prefix url helper had the same parameter---"Parameters:{"action"=>..., "controller"=>..., "person_id"=>3 }".
The "person_id" was excepted to "library_id"!

Then I changed the order of the routing :
map.resources :books,
:path_prefix => '/owner/:library_id',
:name_prefix => 'library_'

map.resources :books,
:path_prefix => '/owner/:person_id',
:name_prefix => 'person_'

This time the parameter "params[:person_id]" didn't work at all when using the helper like "person_new_book(1)" , "person_books (1)",etc.

Seemed in this case , Rails may use the first path-prefix's params for all the next routings whose path-prefix has the same path.

That's quite confused!!