2011-03-18 109 views
1

我有以下幾點:HAS_ONE多態關聯

class Car < ActiveRecord::Base 
    has_one :driver 
end 

class Driver < ActiveRecord::Base 
    belongs_to :car 
    has_one :license, :as => :licensable 
end 

class License < ActiveRecord::Base 
    belongs_to :licensable, :polymorphic => true 
end 

即汽車具有一個司機誰擁有一個許可證(許可證是多態的 - 我們只是在這種情況下說的,因爲它可以與其它對象相關聯) 。

在routes.rb中我有:

resources :cars do 
    resource :driver do 
     resource :license 
    end 
    end 

我想表明我的許可。 「秀」的路線文件是:

GET /cars/:car_id/driver/license(.:format) {:action=>"show", :controller=>"licenses"} 

在我的許可控制我有:

def show 
    @license = @licensable.licenses.find(params[:id]) 
    # continues....... 

的問題是,即使司機有關係執照,@licensable跨到來作爲汽車因爲路線。汽車與許可證沒有關係,因此代碼無效。我想我必須改變我的控制器或更可能我的路線。

回答

1

因爲從URL,你只能得到car_id這可能是工作:

@car = Car.find(params[:car_id]) 
@license = @car.driver.licensable 

另一種方法是使用更少嵌套REST接口。如果許可證和汽車都有唯一的ID,則嵌套並不是真的必要。