【问题标题】:ActiveRecord relationship model with Users and Organizations与用户和组织的 ActiveRecord 关系模型
【发布时间】:2016-07-31 05:14:17
【问题描述】:

我正在尝试找出建模模型之间关系的最佳逻辑方法。 我有 4 个模型:

  1. 用户
  2. 产品
  3. Slack 团队
  4. 组织结构

这里User有很多Products、SlackTeams和Organizations,SlackTeam属于User并且有一个Organization。组织应属于 User 和 SlackTeam。我在这里逻辑正确吗?

工作流程如下:

  • 用户可以使用 SlackTeam(自动创建组织)登录
  • 来自同一 Slack 团队的其他用户在将其帐户与 Slack 关联后将被添加到同一组织中
  • 如果用户连接到许多 SlackTeam(和组织),他们可以过滤以查看他们所属的所有组织的产品或仅来自一个组织的产品

我错过了什么吗?

【问题讨论】:

    标签: ruby-on-rails activerecord


    【解决方案1】:
    class User
      has_many :users_ogranizations
      has_many :organizations, through: :users_organizations
      has_many :products, through: :organizations
    end
    
    class Product
      belongs_to :organization
    end
    
    class Organization
      has_many :users_ogranizations
      has_many :users, through: :users_organizations
      has_many :products
    end
    
    class UsersOrganization
      belongs_to :user
      belongs_to :organization
    end
    
    # i'd rather use slack profile than team, because Organization and Team 
    # already connotes the same thing.
    class SlackProfile
    
    end
    

    您可以随心所欲地处理您的用户登录,不过我更喜欢一种身份验证服务。用户现在可以访问属于该组织的所有产品,然后您可以使用以下内容过滤产品:

    current_user.products.where(organization: Organization.last)
    

    【讨论】:

    • 感谢您的回答。我会测试一下。与您在这里提出的不同的一件事是,在当前数据库中,有记录 Product belongs_to User 和 User has_many Products。我在想这个改变怎么会让旧记录失效。
    • 澄清一下,您的用户可以创建产品吗?因为我在这里的假设是组织创造产品。
    • 哦,是的。作为一个组织的一部分,用户实际上在他们之间共享内容。
    猜你喜欢
    • 2018-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多