天天看點

ROR學習——Active Record

樂觀鎖預設是打開的,當表中有lock_version字段時對該表使用樂觀鎖控制。

使用ActiveRecord::Base.lock_optimistically = false關閉樂觀鎖。

有兩種删除操作delete和destory。差別在于delete不會執行回調和驗證函數,destory則會調用。通常建議使用destory,以保證資料的一緻性。

has_one關聯會自動更新,belongs_to則不會。當賦一個新的對象給has_one關聯時,原有對象的外鍵被置為null。自動更新時即使失敗也不會抛出異常,是以提倡使用a.save!  b.a = a的形式更新資料庫。

ruby 代碼

  1. class User < ActiveRecord::Base   
  2. has_and_belongs_to_many :articles  
  3. def read_article(article)   
  4. articles.push_with_attributes(article, :read_at => Time.now)   
  5. end  
  6. # ...   
  7. end  

ruby 代碼

  1. #使用include來預加載關聯對象   
  2. for post in Post.find(:all, :conditions => "posts.title like '%ruby%'",   
  3. :include => [:author, :comments])   
  4. # ...   
  5. end  

計數器counter,在父表中添加***_count int default 0字段,并在belongs_to中指定:counter_cache = true。但是在手動添加子表中的資料時counter不會自動更新。

ruby 代碼

  1. class LineItem < ActiveRecord::Base      
  2. true     
  3. belongs_to :product, :counter_cache =>      
  4. end     
  5. #counter不會自動更新,需要調用:refresh   
  6. product = Product.create(:title => "Programming Ruby",   
  7. :date_available => Time.now)   
  8. line_item = LineItem.new  
  9. line_item.product = product   
  10. line_item.save   
  11. "In memory size = #{product.line_items.size}"  
  12. puts   
  13. puts "Refreshed size = #{product.line_items(:refresh).size}"  
  14. #This outputs   
  15. #in memory size = 0   
  16. #Refreshed size = 1   
  17. #正确寫法   
  18. product = Product.create(:title => "Programming Ruby",   
  19. :date_available => Time.now)   
  20. product.line_items.create   
  21. puts   
  22. "In memory size = #{product.line_items.size}"  
  23. puts "Refreshed size = #{product.line_items(:refresh).size}"