诗歌rails 之composed_of

ActiveRecord有一个composed_of()方法用来声明组件关系,如:
Java代码
  1. class Person < ActiveRecord::Base
  2. composed_of :address,
  3. :class_name => "Address",
  4. :mapping => [%w(address_street street),
  5. %w(address_city city),
  6. %w(address_state state),
  7. %w(address_country country)]
  8. class Address
  9. attr_accessor :street, :city, :state, :country
  10. def initialize(street, city, state, country)
  11. @street = street
  12. @city = city
  13. @state = state
  14. @country = country
  15. end
  16. end

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

这不会更新person的city字段,因为composed_of()的值对象被认为是immutable的,而只有new一个Address对象才能保存
Java代码
  1. person.address = Address.new(...)
  2. person.save
posted @ 2010-04-08 17:58  麦飞  阅读(539)  评论(0编辑  收藏  举报