2011-12-18 100 views
16

我有以下型號:如何建立一對多的關係?

User (id, name, network_id) 
Network(id, title) 

什麼樣的Rails的模型assoc命令,我需要補充,這樣我可以這樣做:

@user.network.title 
@network.users 

感謝

回答

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 2011-12-18 22:01:19

+7

誠然 :)。只爲未來的讀者,所以他們知道如何添加ID。 – daniel 2011-12-18 22:09:41

+0

有效點,同意。 Upvoted你又對此抱歉:-) – klaffenboeck 2011-12-18 22:24:06

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的設置,你應該與丹尼爾斯回答。

1

這是我的方式: 運行:

$rails generate migration AddNetworkIdToUsers 

然後配置遷移文件:

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 
相關問題