Reputation: 2753
I wrote scope like this
/models/code.rb
scope :recent, lambda { |n = 10| includes(:user).where('users.deleted_at' => nil).order("users.last_active_at DESC").limit(n) }
However, there are the records that have the same users.last_active_at sometimes.
So I tried adding created_at DESC to it like below.
scope :recent, lambda { |n = 10| includes(:user).where('users.deleted_at' => nil).order("users.last_active_at DESC, created_at DESC").limit(n) }
But I get this error. What's wrong with my code? Indeed there is a column called created_at in codes table.
Error (Mysql2::Error: Unknown column 'created_at' in 'order clause'
Upvotes: 0
Views: 45
Reputation: 1684
Since includes decides whether or not the users are joined to the codes table in one SQL query or 2 separate queries are generated (for performance reasons) you should ensure, that you are referring the users table and its created_at column:
scope :recent, lambda { |n = 10| includes(:user).
where('users.deleted_at' => nil).
order("users.last_active_at DESC, users.created_at DESC").
limit(n) }
Also think about merging scopes for responsibility reasons as you can read about here: Merge your ActiveRecord scopes
Upvotes: 1