2011-04-01 80 views
2

我有一個簡單的問題。我無法弄清楚相當於該SQL查詢的軌道:將sql查詢轉換爲rails activerecord

select COUNT(description) from reports where user_id = current_user;

其實我想算總沒有。由特定用戶在登錄其帳戶時發佈的報告,而不是所有用戶發佈的所有報告。 我也無法弄清楚,我應該如何通過登錄的當前用戶的user_id,以便我可以得到所需的結果。 請幫助。

回答

2

喜歡的東西:

current_user.reports.count 
1

在Rails 2

如果在用戶模型中定義has_many :reports

count = current_user.reports.first(:select => "COUNT(description) as count").count 

如果has_many未在模型中定義,

count = Report.first(:select => "COUNT(description) as count", 
      :conditions => {:user_id => current_user.id}).count 

current_user.reports.select{ |report| report.description }.count足夠儘管它產生一個不同的查詢。 (Select * from reports where ..),然後取數組的個數。

但在Rails 3中,這很容易。

如果您在用戶模型中定義了has_many :reports

count = current_user.reports.count(:description) 

否則

count = Report.where(:user_id => current_user.id).count(:description) 

參見Rails guide爲Rails 3 AR計算查詢。