适用范围上的has_many关系的每一个最后的元素 [英] Scope on each last elements of a has_many relation

查看:109
本文介绍了适用范围上的has_many关系的每一个最后的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我有用户和信息之间的has_many关系。

我想设定一个范围,能够通过那些谁有东西在最后一个的消息,他们发布到过滤用户。所以搜索只在每个用户的最后一条消息。

下面我得到的结果的所有消息中...

 类联系与LT;的ActiveRecord :: Base的
    的has_many:消息

    适用范围:filter_by_last_messages,拉姆达{|价值|
        加入(:消息)。凡(?messages.content =,值)
    }
结束
 

解决方案

我理解了它创造的最后一条消息一个belongs_to的关系,在我的User类。

  belongs_to的:last_message,:将class_name => '信息'
 

我在Message类的after_create把我的最后一条消息。 然后我的范围仅仅是如下:

 范围:filter_by_last_messages,拉姆达{|价值|
    加入(:last_message)。凡(?内容=,值)
}
 

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.

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)
}

这篇关于适用范围上的has_many关系的每一个最后的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆