Skip to content

Instantly share code, notes, and snippets.

@wrburgess
Created March 24, 2012 19:37
Show Gist options
  • Save wrburgess/2187164 to your computer and use it in GitHub Desktop.
Save wrburgess/2187164 to your computer and use it in GitHub Desktop.
Setting up a Rails has_many :through relationship with meaningful relationship table #rails #activerecord #relations

##References

##Create Models

Create tables:

rails g model Location
rails g model User
rails g model Checkin

Run migration:

rake db:migrate

Create migration:

rails g migration AddFieldsToTables

##Create Fields

Add to migration file:

class AddFieldsToTables < ActiveRecord::Migration
  def change
    add_column :user, :name, :string
    add_column :location, :name, :string
    add_column :checkin, :user_id, :integer
    add_column :checkin, :location_id, :integer
    add_column :checkin, :source_id: integer
  end
end

Run migration:

rake db:migrate

##Create Relationships

Add to models/location.rb

class Location < ActiveRecord::Base
  has_many :checkins
  has_many :users, :through => :checkins, :uniq => true #if you need unique records
end

Add to models/user.rb

class User < ActiveRecord::Base
  has_many :checkins
  has_many :locations, :through => :checkins, :uniq => true 
end

Add to models/checkins.rb

class Checkin < ActiveRecord::Base
  belongs_to :location
  belongs_to :user
end

##CRUD on has_many :through

Create new relationship

source_id = 1
@user = User.first
@location = Location.first
checkin = Checkin.new user: @user, lap: @lap, source_id: source_id

Count on association

@checkin_count = @user.locations.count
@fernandohgaray
Copy link

Thank you very much!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment