How to setup a one to many relationship?

后端 未结 3 1368
轻奢々
轻奢々 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:58

    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.

提交回复
热议问题