Skip to content

Instantly share code, notes, and snippets.

@bramj
Last active September 25, 2015 09:39
Show Gist options
  • Save bramj/2e15067c982a2f3c4267 to your computer and use it in GitHub Desktop.
Save bramj/2e15067c982a2f3c4267 to your computer and use it in GitHub Desktop.
Rails polymorphic HABTM relation
# The problem: I needed to create bundles, to be able to sell collections of both courses as well as tracks. (and in the future possibly more things)
# But in return, a track/course can also belong to multiple bundles.
# So: bundle has_many tracks/courses, tracks/courses has_many bundles
# (This was work in progress, but if I remember correctly, it works.)
# app/models/bundle.rb
class Bundle < ActiveRecord::Base
# Creating a polymorphic HABTM relation in Rails is not possible,
# this does basically the same thing
has_many :bundles_bundleables # terrible naming
has_many :tracks, through: :bundles_bundleables, source: :bundleable, source_type: 'Track'
has_many :courses, through: :bundles_bundleables, source: :bundleable, source_type: 'Course'
...
end
# app/models/bundles_bundleable.rb
class BundlesBundleable < ActiveRecord::Base
belongs_to :bundle
belongs_to :bundleable, :polymorphic => true
end
# app/models/track.rb
class Track < ActiveRecord::Base
has_many :bundles_bundleables, as: :bundleable
has_many :bundles, through: :bundles_bundleables
...
end
# Same for course.rb as for track.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment