2011-12-18 16 views

答えて

37

のでhas_mayユーザーとユーザーをネットワークbelongs_toネットワーク。

あなたがまだ持っていない場合はnetwork_idを追加してください。foreign_keyにインデックスを付ける価値があるので、それを追加してください。ネットワークモデルで

rails generate migration AddNetworkIdToUsers

class AddNetworkIdToUsers < ActiveRecord::Migration 
    def change 
    add_column :users, :network_id, :integer 
    add_index :users, :network_id 
    end 
end 

ユーザーモデルで

class Network < ActiveRecord::Base 
    has_many :users 
end 

の操作を行います。

class User < ActiveRecord::Base 
    belongs_to :network 
end 
+0

移行の必要性を全く、NETWORK_IDは表にすでに(質問による)である – klaffenboeck

+7

本当のこと:)将来の読者のために、IDを追加する方法を知っています。有効なポイントは – daniel

+0

です。もう一度アップして、ごめんなさい.-) – klaffenboeck

7

データベース・セットアップによると、あなただけの次を追加する必要がありますあなたのモデルへのライン:

class User < ActiveRecord::Base 
    belongs_to :network 
    # Rest of your code here 
end 

class Network < ActiveRecord::Base 
    has_many :users 
    # Rest of your code here 
end 

network_idが設定されていない場合は、danielsの回答を参照してください。

1

これが私のやり方です: 実行:

$rails generate migration AddNetworkIdToUsers 

は、移行ファイル:configと

class AddNetworkIdToUsers < ActiveRecord::Migration[5.1] 

    def up 

    add_column :users, :network_id, :integer 
    add_index :users, :network_id 
    end 

    def down 

    remove_index :users, :network_id 
    remove_column :users, :network_id 
    end 

end