REST nested routes with has_one

Hi everyone,

I have 2 models:

class User < ActiveRecord::Base
has_one :laboratory, :foreign_key => “pi_id”
end

class Laboratory < ActiveRecord::Base
belongs_to :pi, :class_name => “User”, :foreign_key => “pi_id”
end

I set the following routes (in routes.rb):

map.resources :laboratories
map.resources :users, :has_one => :laboratory

All the routes are generated as expected, as demonstrated by rake
routes. In particular:

user_laboratory GET /users/:user_id/laboratory
{:controller=>“laboratories”, :action=>“show”}

But if I try users/17/laboratory, I get a ‘Couldn’t find Laboratory
without an ID’ error. Someone could help me with this?
In advance thank you very much.
Yannis

Yannis J. wrote:

But if I try users/17/laboratory, I get a ‘Couldn’t find Laboratory
without an ID’ error. Someone could help me with this?

In LaboratoriesController#show do you have:

@laboratory = Laboratory.find(param[:id])

or:

if param[:user_id]
@laboratory = User.find(param[:user_id]).laboratory
else
@laboratory = Laboratory.find(param[:id])
end

?

Mark B. wrote:

In LaboratoriesController#show do you have:

@laboratory = Laboratory.find(param[:id])

or:

if param[:user_id]
@laboratory = User.find(param[:user_id]).laboratory
else
@laboratory = Laboratory.find(param[:id])
end

?

Hi Mark,
Of course I had only @laboratory = Laboratory.find(param[:id])
I fixed it and it’s working perfectly now.
Thank you very much!!!
Yannis