Creating Join Tables for has_many & belongs_to Associations
-
01-10-2019 - |
Question
Rails 3 newbie here... I'm working to create a devise auth system that like (yammer) has instances where users belong. I have two tables
Users (email, password...) belongs_to :instance
Instance (domain name, active....) has_many :users
I added the belongs_to and has_many to the models but the schema hasn't been updated to add the join, which I believe would be an instance_id column to the User's table. How does this get accomplished in Rails 3? Thoughts, suggestions?
Solution
You have to add these columns to the schema by migrations.
http://guides.rubyonrails.org/migrations.html
Try:
script/rails generate migration AddInstanceToUsers
then go to your db/migrations folder look for the new file and make it look like:
class AddInstanceToUsers < ActiveRecord::Migration
def self.up
add_column :users, :instance_id, :integer
end
def self.down
remove_column :users, :instance_id
end
end
then run
rake db:migrate
in your console.