我有以下内容:
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
即,Car有一个拥有一个许可证的驱动程序(许可证是多态的 - 在这种情况下我们只能说它可以与其他对象关联)。
在routes.rb中我有:
resources :cars do
resource :driver do
resource :license
end
end
我想出示我的执照。路线文件中的“show”是:
GET /cars/:car_id/driver/license(.:format) {:action=>"show", :controller=>"licenses"}
在我的许可证控制器中,我有:
def show
@license = @licensable.licenses.find(params[:id])
# continues.......
问题在于,即使驾驶员与许可证有关系,但由于路线的原因,@ indeensable也会成为Car。 Car与许可证无关,因此代码不起作用。我想我要么改变我的控制器,要么更改我的路线。
答案 0 :(得分:1)
因为从URL中你只能获得car_id,这可以起作用:
@car = Car.find(params[:car_id])
@license = @car.driver.licensable
另一种方法是使用嵌套较少的REST接口。如果许可证和汽车都具有唯一ID,则不需要嵌套。