兩個協會建立的同桌是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
向消協添加到被稱爲或引薦給客戶使用間接ASSOCATION其他客戶:
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
指示要使用的連接表上的關聯。
來源
2017-09-15 19:19:05
max
我建議你使用你試圖連接表http://guides.rubyonrails.org/active_record_migrations.html#creating-a-join-table –
似乎做一個多對多的關聯,引用作爲連接表。 – EJ2015