简体   繁体   English

has_one到多态关联

[英]has_one to a polymorphic association

I have the following: 我有以下几点:

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

ie, Car has one driver who has one license (license is polymorphic - let's just say in this case since it can be associated with other objects). 也就是说,Car有一个拥有一个许可证的驾驶员(许可证是多态的-在这种情况下,我们可以说它是因为它可以与其他对象关联)。

In routes.rb I have: 在routes.rb中,我有:

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

I would like to show my license. 我想出示我的执照。 The "show" in the routes file is: 路由文件中的“显示”为:

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

In my licenses controller I have: 在我的许可证控制器中,我有:

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

The problem is that even though driver has the relation to license, the @licensable is coming across as Car because of the routes. 问题是,即使驾驶员与许可证有关系,但由于路线的缘故,@ licensable也像Car一样碰到。 Car has no relation to license so the code doesn't work. 汽车与牌照无关,因此代码无效。 I assume I either have to change my controller or more likely my routes. 我想我要么必须更改控制器,要么更可能是我的路线。

Because from the URL you only get the car_id this could work: 因为您只能从URL获得car_id,所以可以这样做:

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

An alternative is to use a less nested REST interface. 一种替代方法是使用嵌套较少的REST接口。 Nesting is not really necessary if licenses and cars both have unique ID's. 如果许可证和汽车都具有唯一的ID,则实际上并不需要嵌套。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM