Ruby on Rails:对同一模型具有不同名称的两个引用 [英] Ruby on Rails: two references with different name to the same model
本文介绍了Ruby on Rails:对同一模型具有不同名称的两个引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的应用程序有一个名为 User
的模型(它包括电子邮件地址、用户名..)我想创建一个模型 Message
它应该有两个字段 sender
和 recipient
.两者都是对 User
模型的引用.我试过这个:
My app has a model called User
(it includes the email adress, username..)
I want to create a model Message
it should have two fields sender
and recipient
. Both are references to the User
model. I tried this:
rails generate model Message sender:references recipient:references
Rails 生成了这个:
Rails generated this:
class Message < ActiveRecord::Base
belongs_to :sender
belongs_to :recipient
end
但我不想要两个不同的模型.这两个字段都应引用 User
.我正在运行 Ruby 2.0.0 和 Rails 4.0.2.任何帮助都受到高度赞赏.如果您需要有关我的问题的更多信息,请询问我.
But I don't want two different models. Both fields should reference to User
. I'm running Ruby 2.0.0 and Rails 4.0.2. Any help is highly appreciated. Please ask me if you need more information about my problem.
推荐答案
可以指定关联的类名,文档
class Message < ActiveRecord::Base
belongs_to :sender, class_name: 'User'
belongs_to :recipient, class_name: 'User'
end
这篇关于Ruby on Rails:对同一模型具有不同名称的两个引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文