如何为多个角色建立关联? [英] How to build associations for multiple roles?

查看:50
本文介绍了如何为多个角色建立关联?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个具有多个角色的 Rails 应用程序.我不能对用户模型使用继承,因为每个角色都有非常不同的属性和行为(即 - 登录后不同的页面访问和能力).所以我决定为每个角色(即客户、服务提供商、客户代表等)构建单独的模型.

I'm building a Rails application with multiple roles. I can't use inheritance against the user model because each role has very different properties and behavior (ie - different page access and abilities once logged in). So I've decided to build separate models for each role (ie - customer, service provider, customer representative, etc).

这项工作的协会将如何运作?我想出了以下内容,但 Role 类对我来说看起来很糟糕.如果用户可以有多个角色,那还不错,但由于他们只有一个角色,我必须在 Role 中编写自定义验证,以确保只选择了一个角色.大家怎么看?

How would the associations for this work? I came up with the following but the Role class just looks bad to me. It wouldn't be so bad if the User could have multiple roles but since they only have one I'd have to write a custom validation in Role ensuring that only one role was selected. What do you guys think?

class User < ActiveRecord::Base
  has_one :role
end

class Role < ActiveRecord::Base
  has_one :customer
  has_one :service_provider
  has_one :customer_representative
end

class Customer < ActiveRecord::Base
end

class ServiceProvider < ActiveRecord::Base
end

class CustomerRepresentative < ActiveRecord::Base
end

推荐答案

我认为这里的问题在于您的角色"模型.角色实际上并不是一个物理的东西,而是一个其他对象应该遵守的接口.因此,它是一种多态关系.

I think the problem here is with your "Role" model. The role isn't actually a physical thing, but an interface that other objects should adhere to. Therefore, its a polymorphic relationship.

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

class Customer < ActiveRecord::Base
  has_one :user, as: :role
end

class ServiceProvider < ActiveRecord::Base
  has_one :user, as: :role
end

class CustomerRepresentative < ActiveRecord::Base
  has_one :user, as: role
end

然后您需要将 role_idrole_type 添加到您的用户表中.

Then you need to add role_id and role_type to your user table.

我相信这应该可以满足您的需求.

This should get your what you want I believe.

这篇关于如何为多个角色建立关联?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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