Scope on each last elements of a has_many relation

耗尽温柔 提交于 2019-12-10 18:35:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!