遵循单一职责原则,我想将一些属性和状态放在一个单独的类中,但是,我希望它在同一个表中。
例子:
class Person
attr_accessible :name, :age
end
class Measures
attr_accessible :weight, :height, :other_attrs
end
如何合成Measures
,Person
将Measure
数据存储在persons
表中?
遵循单一职责原则,我想将一些属性和状态放在一个单独的类中,但是,我希望它在同一个表中。
例子:
class Person
attr_accessible :name, :age
end
class Measures
attr_accessible :weight, :height, :other_attrs
end
如何合成Measures
,Person
将Measure
数据存储在persons
表中?
ActiveRecord 包含一个特定的功能。
class Person
composed_of :measures
end
如果无法从声明中推断出类名,请添加一个class_name
选项。在您的示例中,这不是必需的。如果数据库列不完全映射到Measures 对象的属性,请添加一个:mapping
选项,例如:
composed_of :measures, mapping: %w[database_column_name, object_attribute_name]
如果您想在检索时创建度量或分配新值时执行自定义操作,请分别使用constructor
和converter
选项,并将它们传递给 Proc。这在此处记录。
注意事项:
我不确定这是否适用于rails 4,但在rails 3中你可以做类似的事情
class Measures
self.table_name = 'name_of_the_person_table'
attr_accessible :weight, :height, :other_attrs
end
试试看!