##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
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:
What I tried? well I tried to initialize the relation doing this:
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!