如何建立一对多的关系?

我有以下型号:

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

我需要添加什么样的Rails模型关联才能执行以下操作:

 @user.network.title @network.users 

谢谢

所以网络has_may用户和用户belongs_to网络。

如果你还没有将一个network_id添加到users表,那么因为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 

根据您的数据库设置,您只需将以下行添加到模型中:

 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回答。

这是我的方式:运行:

 $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