I think I understand that only belongs_to association can be
polymorphic. The model that carries belongs_to gets the foreign key
and :polymorphic => true.
But I want to model the following:
A User "has_one" vehicle, which can be either a "Car" or a "Truck",
but not both (this is a requirement). My natural inclination is toward
declaring it thus:
class User < ActiveRecord::Base
class Vehicle < ActiveRecord::Base
class Car < Vehicle
attr_accessible :capacity # no. of passengers it can carry
class Truck < Vehicle
attr_accessible :horse_power # 150, 200, 250 ...
My goal is to be able to have foreign key in the :cars and :trucks
tables in the form of user_id and have no :vehicles table. I of course
want the association methods to work the way they do in class has_one
-- belongs_to combo, i.e. I should be able to do @user.vehicle to mean
either nil or car or truck that user owns, @car.user to be the user
owning that car etc.
I think these expectations are wrong. For instance, since I declared
Vehicle to be an AR model, I need to have :vehicles table. Period. But
when I am modeling the abstractions, I don't need any persistence for
(abstract) Vehicle. I just need to persist either a car or a truck for
a user. Thus, :users table just contains the info relevant to the user
whereas the :cars and :trucks table contains car- and truck-relevant
info along with a user_id foreign key.
Another problem I see with my expectations is that both Car and Truck
must declare belongs_to :user. Period. I am willing to do that, but my
expectation is that since Car is a Vehicle, the belongs_to association
should be inherited by the Car.
Can someone please help me see things more clearly and work around the
issues so that I can capture my relationship succinctly?