ruby-on-rails - 如何为多个角色建立关联?

标签 ruby-on-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

最佳答案

我认为这里的问题在于您的“角色”模型。角色实际上不是物理的东西,而是其他对象应该遵守的接口(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_idrole_type到您的用户表。

我相信这应该得到你想要的。

关于ruby-on-rails - 如何为多个角色建立关联?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11846695/

相关文章:

ruby-on-rails - STI + 命名空间

ruby-on-rails - Rails 3.2 & Devise : custom authenticate_user! 对用户和管理员进行身份验证

ruby-on-rails - Heroku 中的静态只读 SQLite3 数据库

ruby-on-rails - 为什么我得到远程 : sh: 2: Syntax error: Unterminated quoted string when I ran git push heroku master

ruby-on-rails - ruby on rails 无法找到文件 'jquery.ui.all'

ruby-on-rails - 无法在 Rails 中进行验证

ruby-on-rails - Ruby on Rails - 将异常堆栈跟踪添加到 500 错误页面?

ruby-on-rails - 如何在 Rails 应用程序中删除 URL 的尾部斜杠? (在 SEO View 中)

ruby-on-rails - 字符串到序列化数组?

javascript - Ruby on Rails:PDF.JS ActionController::RoutingError(没有路由匹配 [GET] "/pdf js/web/viewer.html"):