The scope for each last element of the has_many relationship

Say I have a has_many relationship between user and posts.

I would like to establish an area in which it will be possible to filter users by those who have something in the last message that they sent. Thus, the search is only among each last message of the user.

Below I got the results among all the posts ...

class Contact < ActiveRecord::Base
    has_many :messages

    scope :filter_by_last_messages, lambda { |value|
        joins(:messages).where("messages.content = ?", value)
    }
end
+3
source share
2 answers

I figured this out by creating a belongs_to relation to the last post in my User class.

belongs_to :last_message, :class_name => 'Message'

I set my last message to after_create in the Message class. Then my scope is as follows:

scope :filter_by_last_messages, lambda { |value|
    joins(:last_message).where("content = ?", value)
}
0
source

, :

scope :last_message, joins(:messages)
         .select("contacts.*, messages.content")
         .order("messages.created_at")

:

if @contact.last_message.content == value
  do_something
end

.

+1

All Articles