更多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 分類目錄。將固定鏈接加入收藏夾。

發表評論