[英]Rails 4: Referral Model Associations
我正在創建一個referral
模型,該模型將能夠鏈接2個客戶端,一個是被推薦的,另一個是進行推薦的。 我已經有了client
模型,但是想知道設置referral
模型的正確方法以便可以查詢:
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
在同一表中設置兩個關聯是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
表示要使用的聯接表上的關聯。 您可以為此使用自我關聯。 在客戶端模型上,添加referrals_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,
}]
現在,您可以查詢引薦,將返回所有引薦具有客戶ID的引薦
Client.find(1).referrals
這將生成類似以下的SQL:
`SELECT "clients".* FROM "clients" WHERE "clients"."referrals_id" = ? [["referrals_id", 1]]`
for Refered_by將返回引用此客戶端的客戶端
Client.find(2).referred_by
這將生成類似以下的SQL:
SELECT "clients".* FROM "clients" WHERE "clients"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.