Sometimes you want your attributes to be more than Strings, Dates and Floats. It is quite simple to just have your attributes instantiated as an object of a custom class.
The approach to achieve the desired effect is to use the composed_of aggregation macro. See also UnderstandingAggregation.
composed_of)class Chocolate < ActiveRecord::Base
# Make optimum_temperature an object of the Temperature class.
# (see class definition below)
composed_of :optimum_temperature, :class_name => "Temperature",
:mapping => %w(optimum_temperature celcius)
end
Read the API docs on Aggregations for further details.
Question: How do you setup the schema for this. What if Temperture has multiple attributes? For instance, if your ActiveRecord object is composed_of Money, and Money has an amount and a currency, what goes in the database?
Answer: ActiveRecord doesn’t save the Money object into the database. All aggregation does, if I understand it correctly, is map the values into the Money object after the data is retrieved. Then, when you’re done, it turns the Money object back into a more simpler form that your database will accept. But, I could be completely wrong :). So, to answer your question, amount and currency would probably go into your database as integer and string, respectively.