Polymorphic one-to-one associations in Rails 3.2 - what's the "correct" Rails way?

Folks,

Unless I’m being dumb I cannot find anything on Google search or in the
Rails books on how to create a one-to-one polymorphic association
(as apposed to a one-to-many polymorphic association). New to Rails so
please forgive my ignorance. The situation is simple: I have the
following models/tables

  • Person
    generic concept (name, age, nationality, etc) which I want to attach
    polymorphically to concrete models suchs

  • Staff

  • Mother

  • Farther

  • Child

  • etc

concrete class contain additional type specific information which I do
not
want nullable hence STI is not desirable
and would result in a sparse table.

If it matters this is for a charity.

Regards, Neil

On 1 August 2012 02:17, Neil M. [email protected]
wrote:

Unless I’m being dumb I cannot find anything on Google search or in the
Rails books on how to create a one-to-one polymorphic association
(as apposed to a one-to-many polymorphic association).

Change the has_many to a has_one, and you should have a 1:1
relationship…

  • Person
    generic concept (name, age, nationality, etc) which I want to attach
    polymorphically to concrete models suchs

concrete class contain additional type specific information which I do not
want nullable hence STI is not desirable
and would result in a sparse table.

I would still consider STI for this kind of situation, but I’d give
each subclass a different association to the specific information for
that model, which would keep the DB nice and ‘clean’ (I did it
yesterday with Vehicles, and sub-classes for Car, Truck, Bus,
Motorbike, etc,)

class Person < AR::Base
end

class Staff < Person

employee number, start date, etc

has_one :staff_details
end

class Mother < Person

can’t imagine what info “mother” would need, but there’s support for

it
has_one :mother_details
end

class Child < Person

what does a child need differently?

has_one :child_details
end

Of course, the problem with this approach is what happens when you
have a staff member who is a mother? You’d need two records for them
(it’s easy for me; a Car can’t also be a Motorbike :slight_smile:
In this event you would be better coming from a different angle (like
a “has_many :employments” to determine whether a Person is staff or
not, and a “has_many :parentings” to figure whether they’re a mother
or father)

HTH

Hello HTH,

Thanks. I must have missed in the doc as I thought one could not put
polymorphic => true on has_one.

Regarding a person having multiple roles (Staff + Mother) I noticed the
issue and was planning on putting
an intermediate Peron -> Role on-to-many in but you way might be easier.

Regards, Neil