【问题标题】:How to setup a one to many relationship?如何建立一对多的关系?
【发布时间】:2011-12-18 21:49:14
【问题描述】:

我有以下型号:

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

我需要添加什么样的 Rails 模型关联才能做到:

@user.network.title
@network.users

谢谢

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 activerecord activemodel


    【解决方案1】:

    so 网络 has_many 用户和用户 belongs_to 网络。

    如果您还没有添加 network_id 到 users 表,并且因为它是一个 foreign_key 值得索引它。

    rails generate migration AddNetworkIdToUsers

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

    在网络模型中做:

    class Network < ActiveRecord::Base
      has_many :users
    end
    

    在用户模型中做:

    class User < ActiveRecord::Base
      belongs_to :network
    end
    

    【讨论】:

    • 不需要迁移,network_id(根据问题)已经在表中
    • 确实如此:)。仅供未来的读者使用,以便他们知道如何添加 id。
    • 现在不应该是add_reference吗?
    • 供参考,在原来的Users create_table迁移中,会是一行"t.references :network, foreign_key: true"
    【解决方案2】:

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

    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
    

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

    【讨论】:

      【解决方案3】:

      这是我的方式: 运行:

      $rails generate migration AddNetworkIdToUsers
      

      然后配置迁移文件:

      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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-20
        • 1970-01-01
        • 1970-01-01
        • 2011-06-19
        • 1970-01-01
        • 2014-11-22
        相关资源
        最近更新 更多