如果我有几个对象,每个对象基本上都有一个Profile
,我用它来存储随机属性,以下是:
- 将序列化的哈希存储在记录的列中,还是
- 存储一堆
belong_to
主对象的键/值对象。
代码
假设您有这样的STI记录:
class Building < ActiveRecord::Base
has_one :profile, :as => :profilable
end
class OfficeBuilding < Building; end
class Home < Building; end
class Restaurant < Building; end
每个has_one: profile
选项1. 序列化哈希
class SerializedProfile < ActiveRecord::Base
serialize :settings
end
create_table :profiles, :force => true do |t|
t.string :name
t.string :website
t.string :email
t.string :phone
t.string :type
t.text :settings
t.integer :profilable_id
t.string :profilable_type
t.timestamp
end
选项2. 键/值存储
class KeyValueProfile < ActiveRecord::Base
has_many :settings
end
create_table :profiles, :force => true do |t|
t.string :name
t.string :website
t.string :email
t.string :phone
t.string :type
t.integer :profilable_id
t.string :profilable_type
t.timestamp
end
create_table :settings, :force => true do |t|
t.string :key
t.text :value
t.integer :profile_id
t.string :profile_type
t.timestamp
end
你会选择哪个?
假设99%的时间我不需要通过自定义“设置”进行搜索。只是想知道在性能和未来问题的可能性方面的权衡。而自定义“设置”的数量可能会在10-50个之间。
我宁愿选择第二个选项,使用设置表,因为它遵循ActiveRecord面向对象的约定。但我想知道在这种情况下,这是否会带来过高的性能成本。
注意:我只关心关系型数据库。这对MongoDB / Redis / CouchDB等非关系型数据库来说是完美的,但我想纯粹了解SQL方面的利弊。