Rails 3 migrations: Adding reference column?

后端 未结 10 2092
余生分开走
余生分开走 2020-11-30 17:15

If I create a new rails 3 migration with (for example)

rails g migration tester title:tester user:references

, everything works fine...howe

10条回答
  •  天命终不由人
    2020-11-30 17:39

    For Rails 4

    The generator accepts column type as references (also available as belongs_to).

    This migration will create a user_id column and appropriate index:

    $ rails g migration AddUserRefToProducts user:references 
    

    generates:

    class AddUserRefToProducts < ActiveRecord::Migration
      def change
        add_reference :products, :user, index: true
      end
    end
    

    http://guides.rubyonrails.org/active_record_migrations.html#creating-a-standalone-migration

    For Rails 3

    Helper is called references (also available as belongs_to).

    This migration will create a category_id column of the appropriate type. Note that you pass the model name, not the column name. Active Record adds the _id for you.

    change_table :products do |t|
      t.references :category
    end
    

    If you have polymorphic belongs_to associations then references will add both of the columns required:

    change_table :products do |t|
      t.references :attachment, :polymorphic => {:default => 'Photo'}
    end
    

    Will add an attachment_id column and a string attachment_type column with a default value of Photo.

    http://guides.rubyonrails.org/v3.2.21/migrations.html#creating-a-standalone-migration

提交回复
热议问题