Skip to content

Instantly share code, notes, and snippets.

@StevenClontz
Forked from wrburgess/gist:2187164
Last active January 18, 2018 21:33
Show Gist options
  • Save StevenClontz/1eb76f761b9114858238dd62d21740a5 to your computer and use it in GitHub Desktop.
Save StevenClontz/1eb76f761b9114858238dd62d21740a5 to your computer and use it in GitHub Desktop.
Setting up a Rails has_many :through relationship with meaningful relationship table #rails #activerecord #relations

Create Models

Create tables:

  • bin/rails g model Location name:string
  • bin/rails g model User name:string
  • bin/rails g model Checkin

Run migration:

  • bin/rails db:migrate

Create Fields

Create migration:

  • bin/rails g migration ConnectLocationsAndUsers

Add to migration file:

class ConnectLocationsAndUsers < ActiveRecord::Migration
  def change
    add_column :checkins, :location_id, :integer
    add_column :checkins, :user_id, :integer
    add_index :checkins, [:location_id, :user_id] #, name: 'index__checkin__location__user' # if index name is too long
  end
end

Run migration:

  • bin/rails db:migrate

Create Relationships

Add to models/location.rb

class Location < ActiveRecord::Base
  has_many :checkins, dependent: :destroy
  has_many :users, through: :checkins 
end

Add to models/user.rb

class User < ActiveRecord::Base
  has_many :checkins, dependent: :destroy
  has_many :locations, through: :checkins 
end

Add to models/checkins.rb

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

CRUD on has_many :through

User.update(location_ids:[])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment