Frodo Larik
2006-May-05 17:27 UTC
[Rails] Adding methods to model based on foreign table rows
Hi all, I wondered if the following is implemented in ActiveRecord: I have three tables: "products", "properties" and "product_properties" the products table holds base information for the product, like product_id, name etc.>> Product.column_names=> ["product_id", "name"] the properties table holds extra "columns" for the products table, but the column "name" in this table should actually be a method for Products>> Property.column_names=> ["property_id", "name", "description", "position"] the third table product_properties holds the mapping data between products and properties>> ProductProperty.column_names=> [ "product_property_id", "product_id", "property_id", "value"] If I do this:>> Property.create(:name => ''color'')I would like to be able to do:>> Product.create(:name => "Glass", :color => "transparent")and>> Product.find(:all, :conditions => ["color=?","transparent"])or>> Product.color=> "transparent" or>> Product.color = "red"where saving/retrieving the "color" method saves/retrieves the values to/from ProductProperties. Is this possible, and if not what is the best place to start coding? -- Sincerely, Frodo Larik
Jeremy Kemper
2006-May-05 22:17 UTC
[Rails] Adding methods to model based on foreign table rows
On May 5, 2006, at 10:26 AM, Frodo Larik wrote:> Hi all, > > I wondered if the following is implemented in ActiveRecord: > > I have three tables: "products", "properties" and "product_properties" > > the products table holds base information for the product, like > product_id, name etc.Active Record does not automatically map multivalued attributes in this way, though it could make a tasty plugin. Do you need to do ad-hoc SQL queries on these attributes? If not, consider serializing a hash of attributes to a single column rather than mapping them to a table.> Is this possible, and if not what is the best place to start coding?Yes; it is possible. Sketch out some unit tests demonstrating the behavior you''d like. Try subclassing ActiveRecord::Base and overriding read_ and write_attribute to work with an has_many :attributes instead of @attributes. Run the tests; repeat. Best, jeremy