2013-08-29 112 views
9

我想用戶參考添加到我的職位表與下面的代碼:未定義的方法「add_reference」

class AddUserIdToPosts < ActiveRecord::Migration 
    def change 
    add_reference :posts, :user, index: true 
    end 
end 

,但我收到一條錯誤消息:

undefined method 'add_reference' 

有誰知道如何解決這個問題?

我使用Rails 3.2.13

+0

這可能幫助? http://stackoverflow.com/questions/4954969/rails-3-migrations-adding-reference-column – dax

回答

16

在Rails 3,你必須這樣做,像這樣

class AddUserIdToPosts < ActiveRecord::Migration 
    def change 
    add_column :posts, :user_id, :integer 
    add_index :posts, :user_id 
    end 
end 

只有在軌道4,你可以做到這一點,你貼的方式。

+0

謝謝路易斯,我不知道這種方法是有效的,只有在Rails 4 –

1

對Rails 4.0

這種方法apperead我想你可以創建具有此功能的一些猴子補丁爲Rails 3.2

2

如何:

def change 
    change_table :posts do |p| 
    p.references :user, index: true 
    end 
end 
3

add_reference是特定於軌道4.0。 0,所以你應該試試這個:

class AddUserIdToPosts < ActiveRecord::Migration 
    def change 
    add_column :posts, :user_id, :integer 
    add_index :posts, :user_id 
    end 
end 

這是一個grea牛逼post有關此主題的

3

你的遷移應該是

rails generate migration AddUserRefToPosts user:references 
+0

這幾乎是我的答案的副本。 :) –

+0

@MarekLipka對不起,我還沒有看到您的文章讓我刪除它 –

+0

@MarekLipka chnage做不了你的副本現在 –