2008年10月30日 星期四

composed_of,model,data object

http://hideto.javaeye.com/blog/77459
http://rorataspire.wordpress.com/2008/07/10/rails-composed_of/
http://api.rubyonrails.org/classes/ActiveRecord/Aggregations/ClassMethods.html#M001663
http://opensoul.org/2006/11/16/making-code-composed_of-code-more-useful


composed_of 感覺就是用來把妳一些 field 在弄成一個 object, 當然也就可以拿這個 value object 產生出新的 object, 也可以用在find 裡面當條件用

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.
9. class Address
10. attr_accessor :street, :city, :state, :country
11. def initialize(street, city, state, country)
12. @street = street
13. @city = city
14. @state = state
15. @country = country
16. end
17. end

  1. person.address = Address.new(...)
  2. person.save
  1. person.address.city = "LA"
  2. person.save
這不會更新person的city字段,因為composed_of()的值對象被認為是immutable的,而只有new一個Address對象才能保存



class UserData
attr_accessor :name

def initialize(name)
@name = name
end
end

class User < ActiveRecord::Base
composed_of :user_data, :mapping =>%w(name name) <= 其實是這樣 ["name", "name"]
end

現在就可以用這樣了
>> u = UserData.new('ilake')
=> #<UserData:0xb7197f28 @name="ilake">
>> User.find(:all, :conditions => {:user_data => u})
=> [#<User id: 5, name: "ilake"]


沒有留言: