[英]Selecting Specific record among multiple records in association Rails
I have a model called User and associated model Message . 我有一个名为User的模型和关联的Message模型。 So user can have many messages. 这样用户可以有很多消息。 I have 4 columns in messages table named sent_at
, opened_at
, clicked_at
and email id
. 我在消息表中有4列,分别名为sent_at
, opened_at
, clicked_at
和email id
。
In message table email id
is not unique. 在消息表中, email id
不是唯一的。 User would have sent multiple emails. 用户将发送多封电子邮件。 So for a user in messages table he can see same email multiple times. 因此,对于邮件表中的用户,他可以多次看到同一封电子邮件。
eg: If user_id
is 7 and I need to find out the recent opened emails using the association. 例如:如果user_id
为7,我需要使用关联找出最近打开的电子邮件。 I need the records of all the users who have opened the mail recently. 我需要最近打开邮件的所有用户的记录。
I used this: 我用这个:
User.find(7).messages.select(*).group(:email_id).having("max(opened_at)")
But its giving men the error. 但是它给了男人错误。
Any help is largely appreciated!! 任何帮助,在很大程度上赞赏! Thanks in advance!! 提前致谢!!
I got the answer after doing lot of research 经过大量研究,我得到了答案
a = User.find(7).messages.order("opened_at,clicked_at”).group_by(&:email_id)
This will return hash. 这将返回哈希。 I will convert this to array using a.to_a and from there I can access the entire active record 我将使用a.to_a将其转换为数组,然后从那里我可以访问整个活动记录
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.