Rails 3 migrations: Adding reference column?

后端 未结 10 2062
余生分开走
余生分开走 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:59

    If you are using the Rails 4.x you can now generate migrations with references, like this:

    rails generate migration AddUserRefToProducts user:references
    

    like you can see on rails guides

    0 讨论(0)
  • 2020-11-30 17:59

    EDIT: This is an outdated answer and should not be applied for Rails 4.x+

    You don't need to add references when you can use an integer id to your referenced class.

    I'd say the advantage of using references instead of a plain integer is that the model will be predefined with belongs_to and since the model is already created and will not be affected when you migrate something existing, the purpose is kind of lost.

    So I would do like this instead:

    rails g migration add_user_id_to_tester user_id:integer
    

    And then manually add belongs_to :user in the Tester model

    0 讨论(0)
  • 2020-11-30 17:59

    You can use references in a change migration. This is valid Rails 3.2.13 code:

    class AddUserToTester < ActiveRecord::Migration
      def change
        change_table :testers do |t|
          t.references :user, index: true 
        end
      end
      def down
        change_table :testers do |t|
          t.remove :user_id
        end
      end
    end
    

    c.f.: http://apidock.com/rails/ActiveRecord/ConnectionAdapters/SchemaStatements/change_table

    0 讨论(0)
  • 2020-11-30 18:02

    You can add references to your model through command line in the following manner:

    rails g migration add_column_to_tester user_id:integer
    

    This will generate a migration file like :

    class AddColumnToTesters < ActiveRecord::Migration
      def change
        add_column :testers, :user_id, :integer
      end
    end
    

    This works fine every time i use it..

    0 讨论(0)
提交回复
热议问题