代码之家  ›  专栏  ›  技术社区  ›  Jeremy Thomas

Rails 4:推荐模型关联

  •  1
  • Jeremy Thomas  · 技术社区  · 7 年前

    referral client 但是我想知道如何正确设置 送交 模型,以便我可以查询:

    Client.find(x).referrals
    # returns all referrals where referrer has the client's id
    
    Client.find(x).referred_by
    # returns client that referred this client
    
    2 回复  |  直到 7 年前
        1
  •  2
  •   max Mike Williams    7 年前

    将两个关联设置到同一个表是ActiveRecord中最复杂的关联之一。关键是为每个外键列设置不同的关联。

    因此,让我们从连接表开始:

    # This is a Rails 5 migration - don't copy paste it
    # You'll have to generate one for rails 4
    class CreateReferrals < ActiveRecord::Migration[5.0]
      def change
        create_table :referrals do |t|
          t.belongs_to :referrer_id, foreign_key: false
          t.belongs_to :referred_id, foreign_key: false
          # Since the table for the foreign key cannot be automatically derived you need to add them manually
          add_foreign_key :referrals, :clients, column: :referrer_id
          add_foreign_key :referrals, :clients, column: :referred_id
          t.timestamps
        end
      end
    end
    

    class Referral < < ActiveRecord::Base
      belongs_to :referrer, class_name: 'Client'
      belongs_to :referred, class_name: 'Client'
    end
    

    这里还没什么可怕的。 class_name: 'Client' 告诉ActiveRecord(AR)关联指向哪个表,因为它不能从关联的名称派生。现在,让我们在客户端上创建反向关联:

    class Client < ActiveRecord::Base
      has_many :referrals, class_name: 'Referral', 
        foreign_key: 'referrer_id'
      has_many :referrals_as_referred, class_name: 'Referral', 
        foreign_key: 'referred_id'
    end
    

    要将关联添加到被引用或引用到客户端的其他客户端,请使用间接关联:

    class Client < ActiveRecord::Base
      # ...
      # clients reffered by this client
      has_many :referred_clients, 
            through: :referrals,
            source: :referred
      has_many :referrers, 
            through: :referrals_as_referred,
            source: :referrer
    end
    
    • through: :referrals 告诉AR通过名为 :referrals .
    • source: :referred
        2
  •  0
  •   Ajinath Jedhe    7 年前

    您可以为此使用自关联。在客户端模型上,添加referrals\u id列。客户端模型中的关联如下:

    class Client < ActiveRecord::Base
      has_many :referrals, class_name: "Client", foreign_key: :referrals_id
      belongs_to :referred_by, class_name: "Client", foreign_key: :referrals_id
    end
    

    假设您在表中有这两条记录。

    [{  
       "id":1,
       "name":"Admin",
       "referrals_id": nil,
     },
     {  
       "id":2,
       "name":"Client",
       "referrals_id":1,
     }]
    

    Client.find(1).referrals
    

    这将生成类似以下的SQL:

    `SELECT "clients".* FROM "clients" WHERE "clients"."referrals_id" = ?  [["referrals_id", 1]]`
    

    for refered\u by will返回引用此客户端的客户端

    Client.find(2).referred_by
    

    这将生成类似以下内容的SQL:

    SELECT  "clients".* FROM "clients" WHERE "clients"."id" = ? LIMIT ?  [["id", 1], ["LIMIT", 1]]