两次参考模型编写迁移 [英] Write a migration with reference to a model twice

查看:32
本文介绍了两次参考模型编写迁移的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个消息模型(Message),这个模型作为一个 userTo 和 userFrom,所以有两个对 User 的引用.我该如何编写迁移?我的用户模型是 User.

I have a message model (Message) and this models as a userTo and userFrom, so two references to User. How can i write the migration? My user model is User.

谢谢

推荐答案

在迁移中,为每种用户创建两个不同的列.例如:

In the migration, create two different columns for each kind of user. For example:

add_column :messages, :sender_id, :integer
add_column :messages, :receiver_id, :integer

然后在模型中,这就是将每一列映射到 User 类的逻辑发生的地方:

Then in the model, that's where the logic to map each column to the User class happens:

belongs_to :sender, :class_name => 'User'
belongs_to :receiver, :class_name => 'User'

当然,senderreceiver 使用你自己的话,但是 Rails 会自动将 sender 关联到 sender_id 列(和 receiver 的逻辑相同)

Of course, use your own words for sender and receiver, but Rails will automatically associate sender to the sender_id column (and the same logic for receiver)

然后您将能够与用户 user.senderuser.receiver 进行交互.

You will then be able to interact with both user user.sender and user.receiver.

这篇关于两次参考模型编写迁移的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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