Rails拥有外部模型

时间:2018-07-06 11:15:03

标签: ruby-on-rails foreign-keys ruby-on-rails-5 ruby-on-rails-5.2

在我的Rails 5.2应用程序中,我想引用另一个模型。我在应用程序中进行了以下设置:

class SomeModule::AnotherModule::User < ApplicationRecord
  has_many :phones
end

class Phone < ApplicationRecord
  belongs_to :user, optional: true, class_name: '::SomeModule::AnotherModule::User'
end

迁移过程如下:

add_reference :phones, :user, foreign_key: true, index: true

现在,当我尝试通过电话呼叫用户时,我得到了:

Phone.first.user
#=> NameError: uninitialized constant User::Phone
from /home/testuser/.rvm/gems/ruby-2.5.1/gems/activerecord-5.2.0/lib/active_record/inheritance.rb:196:in `compute_type'

删除class_name:属性不会更改任何内容。

我在做什么错了?

1 个答案:

答案 0 :(得分:2)

class SomeModule::AnotherModule::User < ApplicationRecord
  has_many :phones, class_name: 'Phone', foreign_key: 'user_id'
end

class Phone < ApplicationRecord
  belongs_to :user, optional: true, class_name: 'SomeModule::AnotherModule::User', foreign_key: 'user_id'
end