简体   繁体   English

Ruby on Rails Active Record关联帮助

[英]Ruby on Rails Active Record associations assistance

I would like to get some suggestions on my Active Record associations. 我想获得有关Active Record关联的一些建议。

I want to make sure they're setup in such a way that I can efficiently call the data needed. 我想确保它们的设置方式可以有效地调用所需的数据。

Models: 楷模:

  • Users 用户
  • Scripts 剧本
  • Commits 提交

  • Users can create scripts, which belong to them. 用户可以创建属于它们的脚本。
  • Then, any user can add commits to any script. 然后,任何用户都可以将提交添加到任何脚本。

Associations: 协会:

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

Some queries I'd like to be able to do: 我想做一些查询:

  • A user can see all scripts that belong to them 用户可以查看属于它们的所有脚本
  • A user can see commits made to a particular script of theirs, and all commits across all their scripts 用户可以看到对其特定脚本所做的提交,以及所有脚本中的所有提交
  • Users can see commits they've made to a particular script, and all commits they've made 用户可以看到他们对特定脚本所做的提交,以及他们所做的所有提交

Hope I explained this clearly enough. 希望我对此解释得足够清楚。

Thanks 谢谢

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
  • This is enough 这就够了

If I understand what you're modeling here, the relationship between User and Script should model ownership, and the indirect relationship through Commit is for contributions. 如果我了解您在此处建模的内容,则UserScript之间的关系应该对所有权进行建模,而通过Commit进行的间接关系就是贡献。 Assuming that's the case, you could add a little more meaning to the relationship names like this: 假设是这种情况,您可以向关系名称添加更多含义,如下所示:

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

Just make the role distinctions clear I'd suggest you do... 请明确角色区分,我建议您这么做...

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM