User can have multiple messages:
class User < ActiveRecord::Base
has_many :messages, :foreign_key => "publisher_id"
end
To get the latest message time I do:
class User < ActiveRecord::Base
def last_message_time
last_message = messages.max{ |m1, m2| m1.created_at <=> m2.created_at }
last_message ? last_message.created_at : nil
end
end
For some reason, I'm sure that there is a better way to do this.
How would you do this ?
This is a short version:
# Ruby < 2.3.0
def last_message_time
messages.order(:created_at).last.try(:created_at)
end
# Ruby >= 2.3.0
def last_message_time
messages.order(:created_at).last&.created_at
end
Update (thx @mnort9): Updated for Ruby > 2.3.0