乐观锁默认是打开的,当表中有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}"