Created
April 27, 2012 15:07
-
-
Save yarinb/2510013 to your computer and use it in GitHub Desktop.
has_many :through
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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