《Rails Recipes》Part II Database Recipes 知识点总结 六

Make Dumb Data Smart with composed_of() 通过composed_of() 使呆板的数据变聪明


基本语法如下

class SomeModel < ActiveRecord::Base
composed_of :some_attribute,

#要添加功能的SomeModel的属性名,
#这个属性可以随便起个名不一定是SomeModel 表中的属性
:class_name => 'SomeSpecialClass' ,
#附带功能的类
#就是他将上面的属性变得“聪明”
#如果与SomeModel 同名可省略设置
:mapping => [%w(model_attr_name special_class_attr)]
#model_attr_name
#原SomeModel 中的属性名(数据库中对应的属性)。
#special_class_attr是'SomeSpecialClass' 中与model_attr_name 对应的属性名
#:mapping也可以设置多个例如
#:mapping => [ %w(address_street street), %w(address_city city) ]


end


下面举个例子
#相当与:class_name => 'SomeSpecialClass'中的'SomeSpecialClass'
class Address
   attr_reader :street, :city
   def initialize(street, city)
     @street, @city = street, city
   end

   def close_to?(other_address)
     city == other_address.city
   end

   def ==(other_address)
     city == other_address.city && street == other_address.street
   end
 end





============================================
customer.address_street = "Hyancintvej"
  customer.address_city   = "Copenhagen"
  customer.address        # => Address.new("Hyancintvej", "Copenhagen")
  customer.address = Address.new("May Street", "Chicago")
  customer.address_street # => "May Street"
  customer.address_city   # => "Chicago"
=============================================

但是对于给@SomeModel.some_attribute.special_class_attr赋值是不会保存的
要新建一个@some_attribute并赋值,然后@SomeModel.some_attribute=@some_attribute才行

你可能感兴趣的:(Ruby,ActiveRecord,Rails)