诗歌rails 之composed_of
ActiveRecord有一个composed_of()方法用来声明组件关系,如:
这样我们就声明Person composed_of Address的关系,这将映射people表的address_street,address_city,address_state和address_country域到Address类,允许你将address作为first-class对象来操作,但是Address类没有继承ActiveRecord::Base,它只是用来结构化数据和面向对象操作。
需要注意的是
这不会更新person的city字段,因为composed_of()的值对象被认为是immutable的,而只有new一个Address对象才能保存
- 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
莫愁前路无知己,天下无人不识君。