原创作者: hideto   阅读:1518次   评论:0条   更新时间:2011-05-26    
ActiveRecord有一个composed_of()方法用来声明组件关系,如:
class Person < ActiveRecord::Base
  composed_of :address,
              :class_name => "Address",
              :mapping => [%w(address_street street),
                           %w(address_city city),
                           %w(address_state state),
                           %w(address_country country)]

class Address
  attr_accessor :street, :city, :state, :country
  def initialize(street, city, state, country)
    @street = street
    @city = city
    @state = state
    @country = country
  end
end

这样我们就声明Person composed_of Address的关系,这将映射people表的address_street,address_city,address_state和address_country域到Address类,允许你将address作为first-class对象来操作,但是Address类没有继承ActiveRecord::Base,它只是用来结构化数据和面向对象操作。
需要注意的是
person.address.city = "LA"
person.save

这不会更新person的city字段,因为composed_of()的值对象被认为是immutable的,而只有new一个Address对象才能保存
person.address = Address.new(...)
person.save
评论 共 0 条 请登录后发表评论

发表评论

您还没有登录,请您登录后再发表评论

文章信息

Global site tag (gtag.js) - Google Analytics