/ ruby

has_many :through => :whaaaaa

Over the weekend I had been working on a new project that I co-founded with a few folks. We are going to be hosting monthly talks with notable figures and others from the Ruby community. We came to the part of our Application where we needed to implement the Event Registration portion of the site. We originally thought about using a HABTM for the association between our Models. We quickly realized that the new "Rails Way" was to use a has_many :through. In many ways this new approach worked out better. Here is a quick Example. Let's use the Event Registration scenario. Let's say we have Users and we have Events as our two Classes. Below is what our User Class may look like.

  class User < ActiveRecord::Base
    has_many :registrations
    has_many :events, :through => :registrations
  end

Then we may have an Event Class like below.

  class Event < ActiveRecord::Base
    has_many :registrations
    has_many :users, :through => :registrations
  end

Finally we get to the bread and butter of this has_many :through wonderfulness. The Join model which we will call Registrations. In the next example will also take a look at the migration to actually create the Registrations table.

  class Registration < ActiveRecord::Base
    validates_uniqueness_of :user_id,:scope => :event_id, :message => "You've already registered."
    belongs_to :user
    belongs_to :event
  end
  class CreateRegistrations < ActiveRecord::Migration
    def self.up
      create_table :registrations do |t|
        t.references :event
        t.references :user

        t.timestamps
      end
    end

    def self.down
      drop_table :registrations
    end
  end