ruby-on-rails – 如何为多个角色建立关联?
发布时间:2020-12-17 02:36:46 所属栏目:百科 来源:网络整理
导读:我正在构建一个具有多个角色的Rails应用程序.我不能对用户模型使用继承,因为每个角色具有非常不同的属性和行为(即 – 登录后不同的页面访问和能力).所以我决定为每个角色建立单独的模型(即 – 客户,服务提供商,客户代表等). 协会将如何运作?我想出了以下内
我正在构建一个具有多个角色的Rails应用程序.我不能对用户模型使用继承,因为每个角色具有非常不同的属性和行为(即 – 登录后不同的页面访问和能力).所以我决定为每个角色建立单独的模型(即 – 客户,服务提供商,客户代表等).
协会将如何运作?我想出了以下内容但是角色课对我来说看起来很糟糕.如果用户可以拥有多个角色,那就不会那么糟糕,但由于他们只有一个角色,我必须在角色中编写自定义验证,确保只选择了一个角色.你们有什么感想? 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 解决方法
我认为这里的问题是你的“角色”模型.角色实际上不是物理的东西,而是其他对象应该遵循的界面.因此,它具有多态关系.
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_id和role_type添加到用户表. 这应该得到你想要的我相信的东西. 乔 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |