Converting a sql query to rails activerecord
I have a simple problem . I am not able to figure out the rails equivalent for this sql query:
select COUNT(description) from reports where user_id = current_user;
Actually I want to count the total no. of reports posted by a particular user when logged in his account and not the开发者_JS百科 all reports posted by all users. I am also not able to figure out that how should I pass the user_id of the current user logged in so that I can get the required result. Please Help.
Something like:
current_user.reports.count
In Rails 2
If you have defined has_many :reports
in User model.
count = current_user.reports.first(:select => "COUNT(description) as count").count
If has_many
is not defined in the model,
count = Report.first(:select => "COUNT(description) as count",
:conditions => {:user_id => current_user.id}).count
But current_user.reports.select{ |report| report.description }.count
is enough though it produces a different query. (Select * from reports where ..
) and then take the count of the array.
But in Rails 3, it is quite easy.
If you have defined has_many :reports
in User model.
count = current_user.reports.count(:description)
otherwise
count = Report.where(:user_id => current_user.id).count(:description)
Refer Rails guide for Rails 3 AR calculation queries.
精彩评论