Rails: sort the model by the last element of the has_many association

I have two models: Userand Message, which are related by relationship has_many. I want to get a list userssorted by timestamp in their last post.

class User < ActiveRecord::Base
  has_many :messages
end
class Message < ActiveRecord::Base
  belongs_to :user
end

When I do this:

@users = User.includes(:messages).order('messages.created_at DESC').limit(5)

It seems to order messages, capture the newest 5 messages, and then return the users associated with them. Thus, the number of users can be less than 5. I want to make sure that I get 5 users.

I want the request to receive the latest message for each request, order the latest messages, and then return the latest messages to users. So I want something like:

@users = User.includes(:messages).order( <messages.last.created_at DESC> )

, paginate. , Postgres.

+4
3

, , phoet, User, last_message_posted_at, touch: true, . , , . (IMO) :

@users = User.all.order(:last_message_posted_at)
=> "SELECT \"users\".* FROM \"users\" ORDER BY \"users\".\"last_message_posted_at\" ASC"

scope: :by_recent_message, ->{ order(:last_message_posted_at) }
User.by_recent_message.limit(5)

, @users. post time , SQL- .

- , -

: http://apidock.com/rails/v4.2.1/ActiveRecord/Persistence/touch

class User < ActiveRecord::Base
  has_many :messages
end
class Message < ActiveRecord::Base
  belongs_to :user, touch: true
end

( ):

@user =  User.includes(:messages).order(updated_at: :desc )
+4

-

Message.group(:user_id).joins(:users).order('max(messages.created_at) desc')
0

you can use left join instead of include

@users = User.joins("LEFT JOIN messages on messages.user_id = users.id").order('messages.created_at').limit(5)
0
source

Source: https://habr.com/ru/post/1629941/


All Articles