How to setup a one to many relationship?

江枫思渺然 提交于 2019-12-03 02:28:40
daniel

so network has_many users and a user belongs_to network.

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.

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

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.

Lanh

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!