Rails: 添加三个模型之间的多态关联

Rails: Adding polymorphic associations between three models

我有三个模型:用户、代理和客户。 目前,

class User < ActiveRecord::Base
  has_one :agency
  has_one :client 
end

class Client < ActiveRecord::Base
  belongs_to :users
end

class Agency < ActiveRecord::Base
  belongs_to :users
end

我想更改关联并创建一个多态关联,如下所示:

User belongs_to :role , :polymorphic => true

Client has_one :user, as: :role
Agency has_one :user, as: :role

我是新手 rails 开发人员。我怎样才能做到这一点?如何编写迁移?

不需要迁移。数据库中的模型之间没有关联(这是迁移会改变的)。

您需要做的是更改模型 app/models/user.rbapp/models/location.rb。只需从用户中删除 belongs_to: 并将其添加到位置:belongs_to: user.

您需要在用户模型中添加两​​个字段,role_idrole_type。您可以按如下方式创建新的迁移

rails g migration addNewFieldsToUsers role_id:integer role_type:string

运行rake db:migrate后需要修改关联如下

class User < ActiveRecord::Base
  belongs_to :role, polymorphic: true          
end

class Client < ActiveRecord::Base
  has_one :user, as: :role, class_name: 'User'  
end

class Agency < ActiveRecord::Base
  has_one :user, as: :role, class_name: 'User'
end

现在重新启动 rails 服务器。