如何使用 Rails 查找一个 has_many 而不是另一个?
消息有_许多用户_消息。它有两个。
1 UserMessage 的发送者为 user_id
另一个 UserMessage 的接收者为 user_id
知道一个用户,对于任何消息,我如何找到另一个用户?
这是我尝试作为 Message 类的方法,但失败了:
32 def other_user(one_user)
33 um = self.user_messages
34 um.each do |user_message|
35
36 output_user = User.find(user_message.user_id) unless user_message.user_id == one_user.id
37 end
38
39 return output_user
40 end
Message has_many user_messages. It has two.
1 UserMessage will have the sender as user_id
The other UserMessage will have the receiver as user_id
Knowing one user, how can I, for any message, find the other?
Here's what I tried as a method to the Message class, but it fails:
32 def other_user(one_user)
33 um = self.user_messages
34 um.each do |user_message|
35
36 output_user = User.find(user_message.user_id) unless user_message.user_id == one_user.id
37 end
38
39 return output_user
40 end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这可以作为关联增强来实现。这对于大量消息来说非常有效,因为它将处理推送到数据库。
This could be implemented as an association enhancement. This will be efficient for high-volume of messages as it pushes processing to DB.
似乎应该更好地定义谁是
发送者
和谁是接收者
,但与此同时,又如何:它需要
集合user_messages
,过滤掉属于one_user
的消息。数组中应该还剩下一个,因此将其取出并返回附加到它的用户。编辑
我可能不明白您的所有要求,但我可能只是将
sender_id
和receiver_id
直接添加到Message
并删除UserMessage
连接表。然后您可以定义如下关系:EDIT 2
如果您想要中间表来跟踪用户特定的状态,您可以考虑使用 STI 将
UserMessage
子类为SentMessageLink
和ReceivedMessageLink
(这些名字并不好——但你明白了),那么你可以使用has_many :through
。对于收到的消息使用类似的代码。然后您应该能够直接从消息访问
sender
和receiver
。It seems like there should be a better definition of who is the
sender
and who is thereceiver
, but in the meantime, what about:It takes the set of
user_messages
, filters out the one that belongs toone_user
. There should be one left in the array, so pick it out and return the user attached to it.EDIT
I might not understand all your requirements, but I'd probably just add a
sender_id
andreceiver_id
directly toMessage
and remove theUserMessage
join table. Then you could define the relationship like:EDIT 2
If you want the intermediate table for tracking user-specific states, you could look into using STI to subclass
UserMessage
asSentMessageLink
andReceivedMessageLink
(those names are not awesome -- but you get the idea), then you could usehas_many :through
.with similar code for received messages. Then you should be able to access
sender
andreceiver
right from the message.