樂觀鎖預設是打開的,當表中有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 代碼
- class User < ActiveRecord::Base
- has_and_belongs_to_many :articles
- def read_article(article)
- articles.push_with_attributes(article, :read_at => Time.now)
- end
- # ...
- end
ruby 代碼
- #使用include來預加載關聯對象
- for post in Post.find(:all, :conditions => "posts.title like '%ruby%'",
- :include => [:author, :comments])
- # ...
- end
計數器counter,在父表中添加***_count int default 0字段,并在belongs_to中指定:counter_cache = true。但是在手動添加子表中的資料時counter不會自動更新。
ruby 代碼
- class LineItem < ActiveRecord::Base
- true
- belongs_to :product, :counter_cache =>
- end
- #counter不會自動更新,需要調用:refresh
- product = Product.create(:title => "Programming Ruby",
- :date_available => Time.now)
- line_item = LineItem.new
- line_item.product = product
- line_item.save
- "In memory size = #{product.line_items.size}"
- puts
- puts "Refreshed size = #{product.line_items(:refresh).size}"
- #This outputs
- #in memory size = 0
- #Refreshed size = 1
- #正确寫法
- product = Product.create(:title => "Programming Ruby",
- :date_available => Time.now)
- product.line_items.create
- puts
- "In memory size = #{product.line_items.size}"
- puts "Refreshed size = #{product.line_items(:refresh).size}"