更多Ruby on Rails的Active Record

Callbacks
class User < ActiveRecord::Base
 before_destroy :dont_destroy_dave
 def dont_destroy_dave
  raise "Can’t destroy dave" if name == ‘dave’
 end
end

class Order < ActiveRecord::Base
 # ..
 def before_save
  self.payment_due ||= Time.now + 30.days
 end
end

class Order < ActiveRecord::Base
 before_validation :normalize_credit_card_number
 after_create do |order|
  logger.info "Order #{order.id} created"
 end
 protected
 def normalize_credit_card_number
  self.cc_number.gsub!(/-w/, ”)
 end
end

Callback Objects 全局可以访问
class CreditCardCallbacks
 # Normalize the credit card number
 def before_validation(model)
  model.cc_number.gsub!(/-w/,”)
 end
end

class Order < ActiveRecord::Base
 before_validation CreditCardCallbacks.new
 # …
end
 Subscription < ActiveRecord::Base
class
 before_validation CreditCardCallbacks.new
 # …
end
可用于数据加密

格式化数据类型:
class LineItem < ActiveRecord::Base
 def total_price
  Float(read_attribute("total_price"))
 end
end

数量单位转换:
class ProductData < ActiveRecord::Base
 CUBITS_TO_INCHES = 18
 def length
  read_attribute("length") * CUBITS_TO_INCHES
 end
 
 def length=(inches)
  write_attribute("length", Float(inches) / CUBITS_TO_INCHES)
 end
end

find_by_sql没有读取PK时不能保存的实例:
result = LineItem.find_by_sql("select quantity from line_items")
result.each do |li|
 li.quantity += 2
 li.save
end

有特殊功能的段名
created_at, created_on, updated_at, updated_on
 ror自动更新的时间段
 修改ActiveRecord::Base.default_timezone = :utc参数更改变时区
lock_version
type
 (employee, manager, person..)
id
XXX_id (FK)
xxx_count
position (acts_as_list)
partent_id (acts_as_tree)

此条目发表在 Ruby on Rails 分类目录。将固定链接加入收藏夹。

发表评论