Direct many-to-many ActiveRecord associations
By using has_and_belongs_to_many you can directly relate models with a many-to-many-association. For example, if you have a model Film and a model Producer, a film can have multiple :producers, and a Producer can have multiple :films; in this case, each of models could have a has_and_belongs_to_many association with the other.
#film.rb
class Film < ApplicationRecord
has_and_belongs_to_many :producers
end
#producer.rb
class Producer < ApplicationRecord
has_and_belongs_to_many :films
end
# Now associative records can be stored and retrieved
film = Film.where(title: "The Irishman")
producer = Producer.where(name: "Martin Scorcese")
film.producers << producer
film.save
producer.films
#=> This should return a collection including The Irishman
films.producers
#=> This should return a collection including Martin Scorcese
Tweet