Search code examples
ruby-on-rails-3model-associations

Multiple associations


I have an event, a vendor, and a venue model.

An event can have multiple vendors but one venue.

A venue can have multiple vendors and multiple events.

A vendor can have multiple venues and multiple events.

I have an events table, a venues table, a vendor table, an events_vendor table and a events_venue table.

How do I have to setup my models?

class Event < ActiveRecord::Base
attr_accessible :name, :budget, :client, :date, :description, :attendees,   
:assets_attributes, :tag_list
belongs_to :user
has_many :assets, :dependent => :destroy
has_many :vendors
has_one :venue
accepts_nested_attributes_for :assets, :allow_destroy => true
acts_as_taggable
end

class EventsVendors < ActiveRecord::Base
  attr_accessible :event_id, :vendor_id
end

class EventsVenues < ActiveRecord::Base
  attr_accessible :event_id, :venue_id
end

class Vendor < ActiveRecord::Base
  attr_accessible :city, :contact, :country, :description, :email, :employees, 
  :latitude, :longitude, :minimum, :name, :state, :street, :tel, :type
  belongs_to :event
end

class Venue < ActiveRecord::Base
  attr_accessible :capacity, :city, :contact, :country, :email, :exclusiveVendors, :fee, 
  :latitude, :longitude, :name, :state, :street, :tel, :union
  belongs_to :event
  has_many :vendors
end

Does my events_venues model belong to both events and venues? Do I have to specify the :through relationship?

Any help would be appreciated. thanks!


Solution

  • Yes, the join tables should look something like this.

    EventsVenues

    belongs_to :event

    belongs_to :venue

    Event

    has_many :venues, through: :events_venues

    has_many :events_venues

    Venues

    has_many :events, through: :events_venues

    has_many :events_venues