2010-09-07 97 views
1

Rails 3新手在這裏...我正在創建一個設計認證系統,就像(yammer)有用戶所屬的實例一樣。我有兩個表爲has_many&belongs_to關聯創建連接表

用戶(電子郵件,密碼......) belongs_to的:例如

實例(域名,活躍....) 的has_many:用戶

我添加了belongs_to的和的has_many模型,但模式尚未更新添加連接,我相信這將是一個instance_id列用戶的表。這在Rails 3中如何實現?想法,建議?

回答

1

您必須通過遷移將這些列添加到架構中。

http://guides.rubyonrails.org/migrations.html

嘗試:

腳本/導軌產生遷移AddInstanceToUsers

然後去你的DB /遷移文件夾中尋找新的文件,並使它看起來像:

class AddInstanceToUsers < ActiveRecord::Migration 

    def self.up 

    add_column :users, :instance_id, :integer 

    end 

    def self.down 

    remove_column :users, :instance_id 

    end 

end 

然後運行

rake db:migrate 

在您的控制檯。

+0

謝謝雪橇,我不需要做任何與參考?出於某種原因,我認爲Rails 3足夠聰明,可以在它看到belongs_to和has_many時自動執行此操作 – AnApprentice 2010-09-07 17:01:59

+0

此外,用戶的instance_id列應該有一個索引。你需要添加另一個遷移來實現嗎? – AnApprentice 2010-09-07 17:12:56

+1

如果更改模型,Rails將在您的模式中不會更改某些內容。您可以在遷移中使用「t.references:instance」,請參閱我發佈的鏈接。如果需要,您可以在相同的遷移中添加索引。只需在add_column後添加「add_index:users,:instance_id」(當然不包括引號)。 – sled 2010-09-07 17:13:16

相關問題