I have a polymorphic PLACE model like this:
class Place < ActiveRecord::Base
belongs_to :placeable, polymorphic: :true
...
So, for example, in my Lodging model I have something like:
class Lodging < ActiveRecord::Base
has_one :place, as: :placeable, dependent: :destroy
...
And they work as expected. The point is that now I want to create a CarRental model and this model has TWO places, on is the pick-up place and the other one is the drop-off place.
So I wrote:
class Transportation < ActiveRecord::Base
has_one :start_place, as: :placeable, dependent: :destroy
has_one :end_place, as: :placeable, dependent: :destroy
And of course that does not work. Any insights on how to do that?
EDIT 1: IF I DO LIKE
class Transportation < ActiveRecord::Base
has_one :start_place, class_name: 'Place', as: :placeable, dependent: :destroy
has_one :end_place, class_name: 'Place', as: :placeable, dependent: :destroy
It works! But why? Where is the start or end information saved?
** EDIT 2: NOPE, IT DOES NOT WORK ** It does not work... =(
I guess, associations spitted out errors before because of the unknown classes.
has_one :start_place
by default assumes you mean a classStartPlace
that doesn't exist. It singularizes the term (as best as it can) and converts it toCamelCase
. Once you've specified that you meanPlace
, it's clear.You should be adding a new column anyways.Let's try single table inheritance (STI). Add a column
type
of typestring
to yourplaces
table:...make sure it does what it says, then migrate and create new models like so:
Note: they don't get a dedicated table and inherit from
Place
, notActiveRecord::Base
. It should generate two empty classes, that's fine, they inherit things fromPlace
....then revert your associations to what didn't work a while ago:
...and they should work now, because
StartPlace
is defined as...same with
EndPlace
with correspondingtype
.I described this quite some time ago for a similar case.