views:

33

answers:

2

Here is the Customer:

   class CreateCustomer < ActiveRecord::Migration

      def self.up 
        create_table :customers do |t|
          t.column :email,        :string, :null => false

        end
      end

      def self.down 
        drop_table :customers
      end
    end

And this is the customer Info:

class CustomerInfo < ActiveRecord::Migration

  def self.up 
    create_table :statuses do |t|
      t.column :statuses,        :string, :null => false

    end
  end

  def self.down 
    drop_table :status
  end
end

What I would like to do is the customer and customer Info have a one to one relationship. How can I do it in a new migration? thank you.

A: 

When you want a 1 to 1 in Rails, you have to decide which one of the models will store the foreign key. In your case, you probably want status to store the fk, so add an integer column called customer_id to the status table. Then you can add the has_one/belongs_to on Customer and Status. belongs_to always goes on the model with the foreign key.

Also I'm not sure if Rails will like you calling your table with the singular name, so you will probably have to do some extra work if you really want to call it 'status' instead of 'statuses'

x1a4
So, I don't need to add extra codes in my Migration? just go to the model, and set the has_one and belongs_to relation, all magic will works?
Tattat
you need to add the foreign key (customer_id) in the migration, but after that, yeah just has_one/belongs_to is it
x1a4
A: 

You can try following thing in your next migration

add_column :customer_infos , :customer_id , :integer ,:references=>"customers" , :null=>:true

Then you can add the has_one/belongs_to on Customer and Cusomer_infos .

You can also execute an SQL statement.

statement = "ALTER TABLE users CHANGE id id SMALLINT( 5 ) UNSIGNED NOT NULL AUTO_INCREMENT" ActiveRecord::Base.connection.execute(statement)

you can entry manually in your migration

Note this is just an example. The final SQL statement syntax depends on the database.