rails find与count

sql语句中存在一些统计函数

如SUM,AVG,MIN,MAX,COUNT等

在rails中一般以

Person.count(num)等形式使用

如:<%=Article.count(:conditions=>{:status=>'pending',:group_id=>g.id})%>
注:记得加=,小因素的忽略会让人很纠结。

下面是find于count的几种用法

#find by id

 Person.find (1)       # returns the object for ID = 1
Person.find(1, 2, 6) # returns an array for objects with IDs in (1, 2, 6)
Person.find([7, 17]) # returns an array for objects with IDs in (7, 17)
Person.find([1]) # returns an array for the object with ID = 1
Person.find(1, :conditions => "administrator = 1", :order => "created_on DESC")

 count

Person.count(:conditions => "age > 26")
Person.count(:conditions => "age > 26 AND job.salary > 60000", :include => :job) # because of the named association, it finds the DISTINCT count using LEFT OUTER JOIN.
Person.count(:conditions => "age > 26 AND job.salary > 60000", :joins => "LEFT JOIN jobs on jobs.person_id = person.id") # finds the number of rows matching the conditions and joins.
Person.count('id', :conditions => "age > 26") # Performs a COUNT(id)
Person.count(:all, :conditions => "age > 26") # Performs a COUNT(*) (:all is an alias for '*')

 

 

find的几种写作形式

 # find first
Person.find(:first) # returns the first object fetched by SELECT * FROM people
Person.find(:first, :conditions => [ "user_name = ?", user_name])
Person.find(:first, :conditions => [ "user_name = :u", { :u => user_name }])
Person.find(:first, :order => "created_on DESC", :offset => 5)

 

# find last
Person.find(:last) # returns the last object fetched by SELECT * FROM people
Person.find(:last, :conditions => [ "user_name = ?", user_name])
Person.find(:last, :order => "created_on DESC", :offset => 5)

# find all
Person.find(:all) # returns an array of objects for all the rows fetched by SELECT * FROM people
Person.find(:all, :conditions => [ "category IN (?)", categories], :limit => 50)
Person.find(:all, :conditions => { :friends => ["Bob", "Steve", "Fred"] }
Person.find(:all, :offset => 10, :limit => 10)
Person.find(:all, :include => [ :account, :friends ])
Person.find(:all, :group => "category")

 这里应该注意点conditions的几种写法

posted @ 2010-12-24 15:53  lonelystarxing  阅读(1407)  评论(0编辑  收藏  举报