How to setup a one to many relationship?
Asked Answered
B

3

28

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:

@user.network.title
@network.users

Thanks

Bobbobb answered 18/12, 2011 at 21:49 Comment(0)
D
62

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
Demonstrate answered 18/12, 2011 at 21:53 Comment(5)
No need for the migration, the network_id is (according to the question) already in the tablePainful
true that :). just for future readers so they know how to add the id.Demonstrate
Shouldn't this be with add_reference nowadays?Diagnose
for reference, in the original Users create_table migration, it would be one line "t.references :network, foreign_key: true"Perfidy
This answer needs to be updated with "add_reference".Buskined
P
9

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.

Painful answered 18/12, 2011 at 21:54 Comment(0)
P
3

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
Proportionate answered 11/1, 2018 at 4:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.