I’m having a bit of a tough time coming up with a good solution for what
I’m trying to do. I’ve come up with a couple of solutions that work
pretty well but many use way too many queries or are just not very good.
Basically I want to store something of a property list for a model.
class Model < AR
has_many :properties, :dependent => :delete
end
class Property < AR
belongs_to :model
belongs_to :property_key
end
|------------------
properties |
---|
id (serial) |
value (varchar) |
property_key_id (int) |
model_id (int) |
------------------ |
Now an issue is that I also store possible KEYs for my properties.
class PropertyKey < AR
has_many :properties, :dependent => :delete
end
|-----------------
property_keys |
---|
id (serial) |
key (varchar) |
----------------- |
I’d like to access a model’s properties somewhat like:
Model.property_key = value # where property_key is dynamic/magic
OR
Model.get_property(key, value)
The problem here is, that with this set up, the way I have it set up, I
have Model#get_property set to this:
def get_property(key)
if key = PropertyKey.find_by_key(key)
self.properties.find(:first, :condition => [“property_key_id = ?”,
key.id]).value
else
false
end
end
and Model#set_property
def set_property(key, value)
if row = properties.find(:first, :conditions => [“properties.key = ?”,
key], :include => :property_key)
if value.empty?
return row.destroy
else
row.value = value
return row.save
end
else
key = PropertyKey.find_by_key(key)
properties << Property.new(:key => key, :value => value) unless
value.empty?
end
end
This is what I have so far. Any help at all would be greatly appreciated
in optimizing this code and making it better! Thanks!!