On May 8, 2006, at 2:29 PM, Alder G. wrote:
would we have a Year model, then get the actual year by Year#year…?
So what’s the Railish take on this? Can you have a has_many
association with the “many” as simple values, not full models? What
did I miss?
This is a case of persisting “values objects” rather than
“entities.” (I like to think of the difference as “would I compare
these by value or by id?”)
Active Record provides the composed_of and serialize class methods to
map columns to custom classes or to store them as YAML.
Using serialize:
create table conventions (id serial primary key, years text);
class Convention
serialize :years, Set
end
foscon = Convention.new
foscon.years << 2005
foscon.save!
foscon[‘years’] == foscon.years.to_yaml
Using composed_of:
Currency = Struct.new(:code)
create table markets (id serial primary key, currency_code char
(3));
class Market
composed_of :currency, :mapping => %w(currency_code code)
end
japan = Market.new(:currency => Currency.new(‘JPY’))
japan.save!
japan.currency_code == ‘JPY’
japan.currency == Currency.new(‘JPY’)
Active Record does not handle mappings such as:
create table conventions (id serial primary key)
create table conventions_years (convention_id not null primary
key references conventions(id), year)
class Conventions
# Returns a Set of 2001, 2002, etc.
has_many :years, :collection => Set, :value => ‘year’
# However, you may:
has_many :convention_years
def years() convention_years.map { |y| y.year }.to_set end
end
Best,
jeremy