问题
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
回答1:
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.
回答2:
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)
}
来源:https://stackoverflow.com/questions/10193922/scope-on-each-last-elements-of-a-has-many-relation