【问题标题】:Ruby on Rails Active Record associations assistanceRuby on Rails Active Record 关联帮助
【发布时间】:2018-01-16 16:19:46
【问题描述】:

我想获得一些关于我的 Active Record 关联的建议。

我想确保它们的设置方式能够有效地调用所需的数据。

型号:

  • 用户
  • 脚本
  • 提交

  • 用户可以创建属于他们的脚本。
  • 然后,任何用户都可以向任何脚本添加提交。

协会:

class User < ApplicationRecord
  has_many :scripts
  has_many :commits
  has_many :scripts, through: :commits
end

class Script < ApplicationRecord
  belongs_to :user
  has_many :commits
  has_many :users, through: :commits
end

class Commit < ApplicationRecord
  belongs_to :script
  belongs_to :user
end

我想做的一些查询:

  • 用户可以查看属于他们的所有脚本
  • 用户可以查看对其特定脚本的提交,以及所有脚本中的所有提交
  • 用户可以查看他们对特定脚本所做的提交,以及他们所做的所有提交

希望我解释得足够清楚。

谢谢

【问题讨论】:

    标签: ruby-on-rails activerecord


    【解决方案1】:

    如果我理解您在这里建模的内容,UserScript 之间的关系应该建模所有权,而通过 Commit 的间接关系是为了贡献。假设是这种情况,您可以像这样为关系名称添加更多含义:

    class User < ApplicationRecord
      has_many :scripts
      has_many :commits
      has_many :contributed_scripts, through: :commits, source: :scripts
    end
    
    class Script < ApplicationRecord
      belongs_to :user
      has_many :commits
    end
    
    class Commit < ApplicationRecord
      belongs_to :script
      belongs_to :user
    end
    

    【讨论】:

    • 对。一个用户拥有脚本,多个用户可以提交,我称他们为脚本用户。史蒂夫的回答会完成相同的关系,只是不同的约定吗?感谢您抽出宝贵时间回复,不胜感激!
    【解决方案2】:
    class User < ApplicationRecord
      has_many :scripts
      has_many :commits, through: :scripts
    end
    
    class Script < ApplicationRecord
      belongs_to :user
      has_many :commits
    end
    
    class Commit < ApplicationRecord
      belongs_to :script
      belongs_to :user
    end
    
    • 这就够了

    【讨论】:

      【解决方案3】:

      只要明确角色区别,我建议你这样做...

      class Script < ApplicationRecord
        belongs_to :user
        has_many :commits
        has_many :contributors, through: :commits, class_name: 'User'
      end
      

      【讨论】:

      • 克里斯的回答是否会实现相同的关系,只是不同的约定?我倾向于这个,因为它在逻辑上/在英语中似乎更有意义。我将他们称为“script_users”,而不是“贡献者”。所以像:“一个脚本有很多 script_users”听起来是对的!感谢您抽出宝贵时间回复,不胜感激!
      • 答案是兼容的,你可能想要两者都做。我回答的问题是给了一个脚本,告诉我所有贡献的人?克里斯给一个用户回答,给我看他贡献的所有脚本?
      • 再次感谢!得到了我想要的东西,并想出了一些更方便的关联