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