Arthur Frankel
Arthur Frankel

Reputation: 4705

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

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.

Upvotes: 1

Views: 5190

Answers (1)

Jaap
Jaap

Reputation: 176

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.

Upvotes: 1

Related Questions