Let’s say I have a has_many relation between User and Messages.
I’d like to set a scope to be able to filter users by the ones who have something in the last message they posted. So searching only among each user’s last message.
Below I got the results among all messages…
class Contact < ActiveRecord::Base
has_many :messages
scope :filter_by_last_messages, lambda { |value|
joins(:messages).where("messages.content = ?", value)
}
end
I figured it out by creating a belongs_to relation with the last message, in my User class.
I set my last message in an after_create in Message class.
Then my scope is simply as follow: