天天看点

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}"