ActiveRecord - automatically merging model data as an aggregate

Sea*_*ary 1 activerecord ruby-on-rails

Lets say I have two tables.

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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

我想让User的contact_info自动合并到我的User对象中作为用户对象的属性,而不必说@ user.contact_info.first_name; 相反,我更愿意能够写@ user.first_name.

我将属性分解到contact_info表的原因是这些是多个模型的常见属性.这就是我将contact_info设置为多态关联的原因.

有谁知道将contact_info的属性直接聚合/合并到我的用户模型中的好方法?

ami*_*kaz 8

使用委托:

class User < ActiveRecord::Base
  has_one :contact_info, :as => :contactable

  delegate :name, :name=, :email, :email=, :to => :contact_info
end
Run Code Online (Sandbox Code Playgroud)

  • 这只是读取委托,如果你还要写,你需要添加setter方法"delegate:name,:email,:name =,:email =" (4认同)