2

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 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.

2 Answers 2

2

Something like:

current_user.reports.count
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.