开发者

has_one to a polymorphic association

I have the following:

class Car < ActiveRecord::Base
  has_one :driver
end

class Driver < ActiveRecord::Base
  belongs_to :c开发者_开发技巧ar
  has_one :license, :as => :licensable
end

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

i.e., 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).

In routes.rb I have:

  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. 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:

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

An alternative is to use a less nested REST interface. Nesting is not really necessary if licenses and cars both have unique ID's.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜