Reputation: 129
I would like to get some suggestions on my Active Record associations.
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
Upvotes: 0
Views: 107
Reputation: 36880
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
Upvotes: 1
Reputation: 1289
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. 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
Upvotes: 1
Reputation: 51
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
Upvotes: 1