Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
@lelandsmith

This comment has been minimized.

Copy link

lelandsmith commented May 14, 2014

I would love to be able to use this but there is a problem with this migration. Can you help me debug this? Thanks!

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

@KanybekMomukeyev

This comment has been minimized.

Copy link

KanybekMomukeyev commented Oct 14, 2014

Maybe we should pluarize here:

class AddFieldsToTables < ActiveRecord::Migration
def change
add_column :users, :name, :string
add_column :locations, :name, :string
add_column :checkins, :user_id, :integer
add_column :checkins, :location_id, :integer
add_column :checkins, :source_id: integer
end
end

@Brotakuu

This comment has been minimized.

Copy link

Brotakuu commented Dec 28, 2015

Sry for the gravedig but also a typo at the end:

add_column :checkins, :source_id, :integer

@dennisdevulder

This comment has been minimized.

Copy link

dennisdevulder commented Feb 19, 2016

Don't forget to add an index to your foreign keys:

add_index :checkins, [:user_id, :location_id]

@delor34n

This comment has been minimized.

Copy link

delor34n commented May 6, 2016

How should I use this in seed.rb? Can you provide an example to use this?

I have a very similar relation between a User model and an Institution model. They are in a many to many relationship, and I followed your gist code and everything is working cool, the database is correctly setup but when I try to load data using seeds I got an error:

NameError: uninitialized constant User::InstitutionsUser

What I tried? well I tried to initialize the relation doing this:

USER = User.create!(
  :usr_rut => 'DNI',
  :usr_name => 'Juanito',
  :usr_lastname_p => 'Mena',
  :usr_lastname_m => 'Gonzalez',
  :email => 'juanitomena@gmail.com',
  :password => 'surewhynot',
  :usr_is_admin => true,
  :user_status_id => ACTIVE_USER.id,
  :user_type_id => ADMIN_USER.id,
  :confirmed_at => DateTime.now
)

INSTITUTION_1 = Institution.create!(
  :ins_name => 'Clínica Alemana',
  :ins_address => 'Av. Pedro de Valdivia 342',
  :ins_phone => 228113245,
  :ins_email => 'clinicalemana@gmail.com',
  :comuna_id => LASCONDES.id,
  :institution_type_id => CLINICA.id
)

USER.institutions << INSTITUTION_1

I'm a rails noobie so my first attempt to setup this was creating a normal/regular many to many relation, not using through. I'm using devise for the user management, but right now I need to build a custom form to include this institution data, and associate the new user with an already created institution, and is not persisting the data to the model, but the form is sending the data to the controller as a User field.

Hope y'all can help me out!

Thanks!

@fdodeJesushdez

This comment has been minimized.

Copy link

fdodeJesushdez commented Sep 21, 2016

Thank you very much!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.