How to setup a one to many relationship?

后端 未结 3 1364
轻奢々
轻奢々 2021-02-05 05:36

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:

3条回答
  •  野的像风
    2021-02-05 05:45

    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
    

提交回复
热议问题