我正在构建一个具有多个角色的 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
最佳答案
我认为这里的问题在于您的“角色”模型。角色实际上不是物理的东西,而是其他对象应该遵守的接口(interface)。因此,它是一种多态关系。
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
到您的用户表。我相信这应该得到你想要的。
乔
关于ruby-on-rails - 如何为多个角色建立关联?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11846695/