[英]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: 楷模:
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: 我想做一些查询:
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
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. 如果我了解您在此处建模的内容,则
User
和Script
之间的关系应该对所有权进行建模,而通过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.