【问题标题】:Are indirect cyclic dependencies ok?间接循环依赖可以吗?
【发布时间】:2015-06-24 15:03:45
【问题描述】:

我正在创建一个 RoR 应用程序,该应用程序需要在同一个表之间进行 多对多 关联(至少在理论上)。

怎么会?好吧,我需要一个 User 表,其中包含两种用户:Serverclient,或多或少类似于老师和学生(有私人课程,但有多名老师),或医生患者

我的第一个想法是简单地创建一个用户表(您知道,登录名、电子邮件和个人信息)并为其分配一个角色(服务器或客户端),但后来我认为制作这种与第三张表的关联会很麻烦

用户 USER_USER

但是创建两个代表每个角色的“登录”表和一个用于关联的第三个表的想法听起来是错误的。

Client_Login Client_Server 服务器

为简单起见,一个客户端不能成为另一个客户端的服务器,一个服务器也不能是另一个服务器的客户端。 显然,一个服务器可以有多个客户端,一个客户端有多个服务器

建议如何建模这种关系?

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4 model-view-controller model


    【解决方案1】:

    如果您需要在服务器和客户端这两者之间显式地使用不同的方法,我假设这是因为您需要不同的类。然后你可能想研究单表继承(STI)。这将允许您使用一个 User 表,但有两个不同的模型使用它。

    class User < ActiveRecord::Base 
        belongs_to :another_model #example association that will exist for all user types
        self.inheritance_column = :role 
        # if you need to be able to tell what role are available
        def self.roles
          %w(Client Server)
        end
    
    end
    
    class Client < User
       has_many :server_clients
       has_many :servers, through: :server_clients
    end 
    class Server < User
       has_many :server_clients
       has_many :clients, through: :server_clients
    end 
    

    然后您只需为网桥设置一个简单的 server_client.rb 模型。

    此处的示例:http://samurails.com/tutorial/single-table-inheritance-with-rails-4-part-1/

    这将允许您将所有用户的通用功能放在 User 类中,并将特定功能放在各自的服务器和客户端类中。

    【讨论】:

      【解决方案2】:

      它一直都在做。多对多回给自己是很常见的。这在处理人与人之间关系的层次结构中很常见,(依赖关系、经理、孩子等......)

      class User
        has_many :user_relations, dependent: destroy, inverse_of: :user
        has_many :dependent_users, through: :user_relations
      
        has_many :dependent_upon_users, through: user_relations, source: 
      :dependent_upon
      end
      
      class UserRelation < ActiveRecord::Base
        belongs_to :user
        belongs_to :dependent_upon, class_name: User
      
        validates_presence_of :user, :dependent_upon
      end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-12-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-04-28
        相关资源
        最近更新 更多