我有一个简单的问题。我无法弄清楚相当于该SQL查询的轨道:将sql查询转换为rails activerecord
select COUNT(description) from reports where user_id = current_user;
其实我想算总没有。由特定用户在登录其帐户时发布的报告,而不是所有用户发布的所有报告。 我也无法弄清楚,我应该如何通过登录的当前用户的user_id,以便我可以得到所需的结果。 请帮助。
我有一个简单的问题。我无法弄清楚相当于该SQL查询的轨道:将sql查询转换为rails activerecord
select COUNT(description) from reports where user_id = current_user;
其实我想算总没有。由特定用户在登录其帐户时发布的报告,而不是所有用户发布的所有报告。 我也无法弄清楚,我应该如何通过登录的当前用户的user_id,以便我可以得到所需的结果。 请帮助。
喜欢的东西:
current_user.reports.count
在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计算查询。