Hey all, I have something of an interesting requirement for my project. I need a has_one
relationship where it is either one class or the other, but without inheritance. I could get away with inheritance if it is the only way, but the two associate records have completely different data and aren't related at all.
What I need to figure out is something like the following.
# 1. Foo never belongs to anything.
# 2. Foo MUST have one assigned sub-record for validity.
# 3. Foo can only have either Bar or Baz assigned.
# 4. Bar and Baz have only ONE common property, and aren't
# related in either data or implementation.
class Foo < ActiveRecord::Base
# Attributes: id, name, value
has_one :assignment, :foreign_key => 'assigned_to', :readonly => true
# Could really use an :object_type for has_one here...
end
class Bar < ActiveRecord::Base
# Attributes: name,...
end
class Baz < ActiveRecord::Base
# Attributes: name,...
end
Where Foo
has one assignment, of type either Bar
or Baz
; they only share one common column, so perhaps I can make a parent object from that. However, if I make them inherit from a common object (when the data they contain really is oranges and apples) must I make a table for the record? Can I perhaps get away with it if the record is an abstract record, but the children aren't?
I suppose by now you can see my difficulty. I'm rather new to RoR but loving it so far. I'm sure there's a way around this, but I'll be darned if I can't figure out what it is.