Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allow users to create dynamic model attributes?

In my Rails3 app, I am using ActiveRecord and Postgresql.

Say I have a model called Parts. The model has a small list of standard attributes such as price, quantity, etc.

However, Customer A might want to add LotNumber and CustomerB might want to add OriginalLocation.

How would I allow them to do that?

I thought about creating a PartsDetail model that allowed them to have a type.

class PartsDetail < ActiveRecord::Base
    attr_accessible :type, :value, :part_id
    belongs_to :parts
end

So that "type" could be "LotNumber", etc.

But I'm not quite sure how that would work in my associations and querying.

Any ideas?

Thanks.

like image 883
cbmeeks Avatar asked Jan 31 '26 21:01

cbmeeks


1 Answers

Since you're using PostgreSQL, you could use hstore to store arbitrary hashes in database columns:

This module implements the hstore data type for storing sets of key/value pairs within a single PostgreSQL value. This can be useful in various scenarios, such as rows with many attributes that are rarely examined, or semi-structured data. Keys and values are simply text strings.

There's even a gem for adding hstore support to ActiveRecord:

https://github.com/softa/activerecord-postgres-hstore

Then you could create an hstore column called, say, client_specific and look inside it with things like:

M.where("client_specific -> 'likes' = 'pancakes'")
M.where("client_specific @> 'likes=>pancakes'")

to see which clients have noted that they like pancakes.

You might want to store a list of customer-specific fields somewhere with the customer record to make the UI side of things easier to deal with but that's pretty simple to do.

like image 177
mu is too short Avatar answered Feb 02 '26 13:02

mu is too short



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!