Skip to content

Instantly share code, notes, and snippets.

@yarinb
Created April 27, 2012 15:07
Show Gist options
  • Save yarinb/2510013 to your computer and use it in GitHub Desktop.
Save yarinb/2510013 to your computer and use it in GitHub Desktop.
has_many :through
class User < ActiveRecord::Base
attr_accessible :name
has_many :bookings
has_many :events, :through => :bookings
end
class Event < ActiveRecord::Base
attr_accessible :title
has_many :bookings
has_many :users, :through => :bookings
end
# This is the join model...
class Booking < ActiveRecord::Base
belongs_to :user
belongs_to :event
attr_accessible :role
end
user = User.create(name: "A User")
event = Event.create(title: "An Event")
user.events << event # works as expected but creates a Booking instance with 'nil' role.
booking = Booking.create(role: "Admin")
user.bookings << booking
event.bookings << booking
# done deal
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment