AakLak
AakLak

Reputation: 129

Ruby on Rails Active Record associations assistance

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

Answers (3)

SteveTurczyn
SteveTurczyn

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

Chris Kottom
Chris Kottom

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

vishnuprakash
vishnuprakash

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
  • This is enough

Upvotes: 1

Related Questions