Ruby-on-rails 如何建立一对多的关系?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8555082/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 02:30:43  来源:igfitidea点击:

How to setup a one to many relationship?

ruby-on-railsruby-on-rails-3activerecordactivemodel

提问by AnApprentice

I have the following models:

我有以下型号:

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

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

我需要添加什么样的 Rails 模型 assoc 以便我可以:

@user.network.title
@network.users

Thanks

谢谢

回答by daniel

so network has_manyusers and a user belongs_tonetwork.

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

Just add a network_idto users table if you still haven't and also since it's a foreign_keyis worth indexing it.

network_id如果您还没有,只需将 a 添加到 users 表,并且因为它foreign_key值得对其进行索引。

rails generate migration AddNetworkIdToUsers

rails generate migration AddNetworkIdToUsers

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

In the network model do:

在网络模型中:

class Network < ActiveRecord::Base
  has_many :users
end

In the user model do:

在用户模型中:

class User < ActiveRecord::Base
  belongs_to :network
end

回答by klaffenboeck

According to your database-setup, you just have to add the following lines to your models:

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

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

In case you have a setup without network_id, you should go with daniels answer.

如果您的设置没有 network_id,您应该使用 daniels 的答案。

回答by hula-san

This is my way: run:

这是我的方式:运行:

$rails generate migration AddNetworkIdToUsers

then config migration file:

然后配置迁移文件:

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