可以说我有两个表。 ActiveRecord - 自动合并模型数据作为一个聚合
class CreateUsers < ActiveRecord::Migration
def self.up
create_table :users do |t|
t.string :type, :default => 'User'
t.string :user_name, :null => false
t.boolean :is_registered, :default => true
# ... many more fields
end
end
end
class CreateContactInfo < ActiveRecord::Migration
def self.up
create_table :contact_info do |t|
t.integer :resource_id
t.string :resource_type
t.string :first_name
t.string :last_name
t.string :middle_initial
t.string :title
end
end
end
class ContactInfo < ActiveRecord::Base
belongs_to :contactable, :polymorphic => true
end
class User < ActiveRecord::Base
has_one :contact_info, :as => :contactable
# composed_of :contact_info # ... It would be nice if magics happened here
end
我想有用户的contact_info自动合并到我的用户对象为用户对象的属性,而不必说@ user.contact_info.first_name;相反,我更愿意写@ user.first_name。
我将属性分解到contact_info表的原因是它们是多个模型的通用属性。这就是为什么我要将contact_info设置为多态关联。
有谁知道一个很好的方法来将contact_info的属性直接聚合/合并到我的用户模型中吗?
感谢编辑,使其更容易阅读的代码:-) – 2010-01-08 21:03:25