Ruby on Rails:对同一模型具有不同名称的两个引用

问题描述:

我的应用程序有一个名为 User 的模型(它包括电子邮件地址、用户名..)我想创建一个模型 Message 它应该有两个字段 senderrecipient.两者都是对 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