Forum: Ruby on Rails Adding methods to model based on foreign table rows

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Frodo L. (Guest)
on 2006-05-05 21:29
(Received via mailing list)
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 L.
Jeremy K. (Guest)
on 2006-05-06 02:18
(Received via mailing list)
On May 5, 2006, at 10:26 AM, Frodo L. 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
This topic is locked and can not be replied to.