MKK
MKK

Reputation: 2753

How can I code this with less SQL queries?

These code outputs 2 sql queries.

@trackings = Tracking.where(:target_user_id => current_user.id ).page(params[:page]).per(10)
@trackings_count = Tracking.where(:target_user_id => current_user.id ).count

To make it less, how can I code?

something like this?

@trackings = Tracking.where(:target_user_id => current_user.id )
@trackings_count = @trackings.count
@trackings = @trackings.page(params[:page]).per(10)

Upvotes: 0

Views: 52

Answers (2)

hawk
hawk

Reputation: 5408

My solution (One query). I guess you using kaminari gem :

@trackings = Tracking.where(:target_user_id => current_user.id).to_a
@trackings_count = @trackings.length
@trackings = Kaminari.paginate_array(@trackings).page(params[:page]).per(10)

Upvotes: 1

Aman Garg
Aman Garg

Reputation: 4218

Use counter_cache. It will help you save multiple queries. You need not to run another query for count.

http://railscasts.com/episodes/23-counter-cache-column

Upvotes: 1

Related Questions