如何建立一对多关系? [英] How to setup a one to many relationship?

查看:116
本文介绍了如何建立一对多关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下模型:

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

我需要添加哪种Rails模型关联才能执行:

What kind of Rails model assoc do I need to add so that I can do:

@user.network.title
@network.users

谢谢

推荐答案

所以网络 has_many 用户和用户属于网络。

so network has_many users and a user belongs_to network.

只需添加如果仍然没有,则将它添加到用户表中,并且由于它是 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
end

在用户模型中:

class User < ActiveRecord::Base
  belongs_to :network
end

这篇关于如何建立一对多关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆