pierrea
pierrea

Reputation: 1487

Scope on each last elements of a has_many relation

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

Upvotes: 3

Views: 865

Answers (2)

pierrea
pierrea

Reputation: 1487

I figured it out by creating a belongs_to relation with the last message, in my User class.

belongs_to :last_message, :class_name => 'Message'

I set my last message in an after_create in Message class. Then my scope is simply as follow:

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

Upvotes: 0

Eric Sites
Eric Sites

Reputation: 1534

Doing this in one shot in a scope is not possible but you could do this:

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

In your controller:

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

So a little bit can be scoped.

Upvotes: 1

Related Questions