简体   繁体   中英

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:

  • 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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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