Ruby新手在这里。首先,这比实际更具哲学性,所以如果有更好的方法来实现这一点,请告诉我们。
我的表格看起来大致如下:
╔════╦════════╦════════╦══════════╗
║ ID ║ label ║ value ║ thing_id ║
╠════╬════════╬════════╬══════════╣
║ 1 ║ color ║ red ║ 1 ║
║ 2 ║ size ║ medium ║ 1 ║
║ 3 ║ weight ║ heavy ║ 1 ║
╚════╩════════╩════════╩══════════╝
我查询这个并获得特定事物的记录集。
thing_attributes = ThingAttributes.where(:thing_id => 1)
导致该表中的5行左右的记录集。我希望能够创建一个允许我创建相当于{"color" => "red", "size" => "medium", "weight" => "heavy" }
的has。想法?
答案 0 :(得分:2)
好的,基本上你是在试图模仿无模式数据库,因为你希望你的不同记录具有不同的属性。只要您只有一个自定义属性pr。记录,这可能会有效,但是如果您的记录中的属性多于常见的,那么您可能需要考虑使用多个模型,查看hstore数据类型或查看文档数据库,例如MongoDB。
再次阅读你的问题,我想我有一个更好的解决方案,所以我删除了原来的一个。
我将调用你的ThingAttributes类,我认为它是一个CustomAttribute类。因为每条记录代表一个自定义属性。一件事可以有很多(在你的例子中是五个)自定义属性。
所以你可以这样做:
class CustomAttribute < ActiveRecord::Base
belongs_to :thing
attr_accessible :name, :value
end
class Thing < ActiveRecord::Base
has_many :custom_attributes
end
现在你可以通过写
找到一件事my_thing = Thing.find(3)
然后,您可以通过编写
找到它的custom_attributesmy_thing.custom_attributes
这将返回一组自定义属性。但是,您(由于某种原因)要求哈希。这也可以做到。在你的Thing类中,定义这个方法:
def custom_attributes_hash
custom_hash = {}
self.custom_attributes.each do |attr|
custom_hash[attr.name] = attr.value
end
custom_hash
end
现在,您可能希望能够以方便的方式设置属性。在你的Thing课上定义它。
def set_custom_attribute(name, value)
return unless name.present? # Short circuits method if an empty string or nil is being used as name.
custom_attribute = self.custom_attributes.find_by_name(name) # Attemps to find custom attribute with the name
if custom_attribute.nil? # Executes block if no attribute was found
return unless value.present? # Short circuits method if nil or empty string was passed as value
self.custom_attributes.create(name: name, value: value) # Creates and saves new custom attribute
else
if value.present? # Updates existing attribute if passed is not an empty string or nil.
custom_attribute.update_attribute(:value, value)
else
custom_attribute.destroy # Deletes custom attribute from DB if set_custom_attribute was called with a nil or empty value.
end
end
end
答案 1 :(得分:0)
我不确定自己是否康复,但试试这个:
my_thing = Thing.find(1)
my_thing.color
答案 2 :(得分:0)
我认为这就是你要求的:
Thing_model.rb
thing = Thing.find(1)
def #{self.label}
return self.value