Rails中,如何设置一个一对多的关系? [英] Rails, how to setup a one to many relationship?
本文介绍了Rails中,如何设置一个一对多的关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下型号:
User (id, name, network_id)
Network(id, title)
什么样的Rails的模型assoc命令,我需要补充,这样我可以做的:
What kind of Rails model assoc do I need to add so that I can do:
@user.network.title
@network.users
感谢
推荐答案
让网络has_may用户和用户belongs_to的网络。
so network has_may users and user belongs_to network.
只是一个NETWORK_ID添加到用户表,如果你还没有,也因为它是一个foreign_key值得索引它。
Just add a network_id to users table if you still haven't and also since it's a foreign_key is worth indexing it.
导轨产生迁移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
在用户模式:
in the user model:
class User < ActiveRecord::Base
belongs_to :network
这篇关于Rails中,如何设置一个一对多的关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文