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.   
  6. #counter不会自动更新,需要调用:refresh   
  7. product = Product.create(:title => "Programming Ruby",   
  8. :date_available => Time.now)   
  9. line_item = LineItem.new  
  10. line_item.product = product   
  11. line_item.save   
  12. "In memory size = #{product.line_items.size}"  
  13. puts   
  14. puts "Refreshed size = #{product.line_items(:refresh).size}"  
  15. #This outputs   
  16. #in memory size = 0   
  17. #Refreshed size = 1   
  18.   
  19. #正确写法   
  20. product = Product.create(:title => "Programming Ruby",   
  21. :date_available => Time.now)   
  22. product.line_items.create   
  23. puts   
  24. "In memory size = #{product.line_items.size}"  
  25. puts "Refreshed size = #{product.line_items(:refresh).size}"  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值