Ruby on rails - 两次引用同一个模型? [英] Ruby on rails - Reference the same model twice?

查看:39
本文介绍了Ruby on rails - 两次引用同一个模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以通过 generate scaffold 命令在 activerecord 模型中建立双重关系?

Is it possible to set up a double relationship in activerecord models via the generate scaffold command?

例如,如果我有一个 User 模型和一个 PrivateMessage 模型,private_messages 表将需要跟踪 sender收件人.

For example, if I had a User model and a PrivateMessage model, the private_messages table would need to keep track of both the sender and recipient.

显然,对于单一关系,我会这样做:

Obviously, for a single relationship I would just do this:

ruby script/generate scaffold pm title:string content:string user:references

有没有类似的方法可以建立两个关系?

Is there a similar way to set up two relations?

另外,有没有办法为关系设置别名?

Also, is there anyway to set up aliases for the relations?

所以与其说:

@message.user

您可以使用以下内容:

@message.sender@message.recipient

任何建议将不胜感激.

谢谢.

推荐答案

将此添加到您的模型

belongs_to :sender, :class_name => "User"
belongs_to :recipient, :class_name => "User"

并且您可以调用 @message.sender@message.recipient 并且都引用 User 模型.

And you are able to call @message.sender and @message.recipient and both reference to the User model.

在您的生成命令中,您需要 sender:referencesrecipient:references

Instead of user:references in your generate command, you'd need sender:references and recipient:references

这篇关于Ruby on rails - 两次引用同一个模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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