One-to-one polymorphic rails model

Can someone help me work out what is best practice for initializing
the objects in a one-to-one polymorphic rails model, or just explain
whayt goes on in the background.

Let me give you a silly example model representing staff and students
which all have canteen charge cards provided when they join.

class Staff < ActiveRecord::Base
has_one :charge_card, :as => :chargable

class Student < ActiveRecord::Base
has_one :charge_card, :as => :chargable

class ChargeCard < ActiveRecord::Base
belongs_to :chargable, :polymorphic => true

I would have thought that somewhere under the covers;

s = Staff.create( :ref => “ST72913”, :name => “John S.”)

would have created and saved to the database, not only the staffer,
but also a default charge card object.

However the only way I can figure to do that is to do:

s = Staff.create( :ref => “ST72913”, :name => “John S.”)
s.create_charge_card( :balance => 0 )

which is not quite the voodoo that I would have expected.

Can anyone explain what I’m doing wrong, or explain why I’m so stupid
as to think that is the way it should work in the first place?

Groove on and thanks.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs