ubuntu, ror, jQuery, css, website memo
太嫩, 沒啥心得, 用來紀錄每天學的
2009年2月5日 星期四
Activerecord memo (2)
Find的參數
1.select
#select 可以只選出我們想要的
f = Forum.find(:all, :joins => :user, :select => "forums.*, users.name")
#如果參數是設成 :select => "*" 那麼users全部的attributes 也會被select 進去
>> f[0].attributes
=> {"name"=>"iflakela", "last_comment_time"=>Sat Aug 23 19:34:17 +0800 2008, "public"=>nil, "subject"=>"111111111", "id"=>6, "group_id"=>1, "content"=>"11111111", "user_id"=>1, "comments_count"=>2, "created_at"=>Sat Aug 23 19:19:02 +0800 2008}
>> f[0].attribute_names
=> ["comments_count", "content", "created_at", "group_id", "id", "last_comment_time", "name", "public", "subject", "user_id"]
#判斷有沒有這個attribute
>> f[0].attribute_present?("lala")
=> fales
2.group
Forum.find(:all, :group => 'DATE(created_at)', :select => "subject, DATE(created_at)")
SELECT subject, DATE(created_at) at FROM `forums` GROUP BY DATE(created_at);
+--------------------------+-----------------+
| subject | DATE(created_at) |
+--------------------------+-----------------+
| 111111111 | 2008-08-23 |
| cc | 2008-08-27 |
| aaaaaaaaaaaaa | 2008-08-29 |
| a | 2008-09-03 |
| dddddddd | 2008-12-07 |
| 333333333333 | 2008-12-13 |
| 1111111 | 2008-12-14 |
| lalalal | 2008-12-28 |
統計的method
有average, maximum, minimum, sum, count
1. count, group
#每天forum 的數目
>> Forum.count(:all, :group => 'DATE(created_at)')
=> [["2008-08-23", 6], ["2008-08-27", 1], ["2008-08-29", 1], ["2008-09-03", 1], ["2008-12-07", 3], ["2008-12-13", 2], ["2008-12-14", 3], ["2008-12-28", 3], ["2009-01-03", 2], ["2009-01-08", 1]]
2. maximum
Status.maximum :score, :group => "user_id", :limit => 3, :order => "max(score) desc"
=> [[2, 3], [4, 3], [6, 2]]
SELECT max(`statuses`.score) AS max_score, user_id FROM `statuses` GROUP BY user_id ORDER BY max(score) desc LIMIT 3;
+-----------+---------+
| max_score | user_id |
+-----------+---------+
| 3 | 2 |
| 3 | 4 |
| 2 | 6 |
+-----------+---------+
memo: find_by_sql, count_by_sql
u = User.find_by_sql("select * from forums, users where forums.user_id=users.id")
count = LineItem.count_by_sql("select count(*) " +
" from line_items, orders " +
" where line_items.order_id = orders.id " +
" and orders.name = 'Dave Thomas' " )
find_or_initialize_by, find_or_create_by
沒有留言:
張貼留言
較新的文章
較舊的文章
首頁
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言