Ruby on rails开发从头来(四十九)- ActiveRecord基础(行数和再加载数据)
Posted on 2008-04-09 09:36 Cure 阅读(1982) 评论(0) 编辑 收藏 举报 Active Record提供了两个方法来获取符合条件的记录的条数:count()和count_by_sql()。例如:
c1
= Order.count
c2
= Order.count(["name = ?", "Dave Thomas"])
c3
= LineItem.count_by_sql("select count(*) " +
" from line_items, orders " +
" where line_items.order_id = orders.id " +
" and orders.name = 'Dave Thomas' ")
puts
"Dave has #{c3} line items in #{c2} orders (#{c1}
orders in all)"
在一个程序中,数据库有可能被多个进程或多个程序访问,随时都有可能获取最新的Model对象,这些对象有可能刚刚被编辑过。
从某种程度上讲,这主要应用在事务中,不管怎么说,当你需要手动刷新Model对象时,Active
Record可以帮助你,只需调用reload()方法,Model对象属性的值就会被数据库中的值更新。
stock
= Market.find_by_ticker("RUBY")
loop
do
puts
"Price = #{stock.price}"
sleep
60
stock.reload
end