views:

27

answers:

1

Hello, 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?

+1  A: 

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.

sled
Thanks Sled, I don't need to do anything with references? For some reason I thought Rails 3 was smart enough to do this automatically when it sees the belongs_to and has_many
AnApprentice
Also, the user's instance_id column should have an index. Do you need to add another migration to make that happen?
AnApprentice
Rails will _never_ change something in your schema if you change the model. You can use "t.references :instance" in your migration, see the link I posted. You can add the index in the same migration if you want. Just add the line "add_index :users, :instance_id" (without quotes of course) after the add_column.
sled
shoot I already the migration. Does that mean it's to late to add the index?
AnApprentice
yep.. just create another one or do a rollback, change it, and remigrate. I'd recommend to create a new migration.
sled
So something like: script/rails generate migration AddInstanceIndexToUsers, then making sure the index is in the migration file, then running db:migrate? Is that it?
AnApprentice
yes that's it. The name of the migration doesn't follow a convention by the way. You can name it anyway you want.
sled
That worked, thanks for your help. I learned a ton!
AnApprentice