我有一個模型(旅行),我想與其他類型(其他旅行)有關。用於鏈接同一模型的兩條記錄的ActiveRecord關係聲明? (自我參照多對多)
使用連接模型存儲兩個trip_id值和強度值(表示關係強度)。
是什麼讓我的情況棘手是關係是一種雙向關係。所以他們不是這種關係的「所有者」。我想採取@trip_a並要求@ trip_a.trip_relations查找所有相關行程。同樣,我想要求@ trip_b.trip_relations。
代碼可能有助於解釋:
class TripRelation < ActiveRecord::Base
belongs_to :trip_a, :class_name => "Trip", :foreign_key => "trip_a_id"
belongs_to :trip_b, :class_name => "Trip", :foreign_key => "trip_b_id"
end
class Trip < ActiveRecord::Base
has_many :trip_a_relations, :class_name => "TripRelation", :foreign_key => "trip_a_id"
has_many :trip_b_relations, :class_name => "TripRelation", :foreign_key => "trip_b_id"
has_many :trip_as, :through => :trip_a_relations
has_many :trip_bs, :through => :trip_b_relations
end
以上不工作,但希望有助於說明意圖。
我希望能夠採取任何行程並要求@ trip.trip_relations並獲取@ trip.trip_as和@ trip.trip_bs(刪除重複項)的列表。
我也想採取任何行程,並建立像@ trip_a.trip_relations < < @trip_b的關係。現在@ trip_a.trip_relations.include?(@ trip_b)#=> true和@ trip_b.trip_relations.include?(@ trip_b)#=> true。
我可以寫一個自定義方法,但我想知道是否有辦法用ActiveRecord乾淨地做到這一點。
,完美處理它。它有一段時間沒有更新,但似乎與我的Rails 3應用程序正常工作。謝謝scrags。 – nutcracker 2011-01-20 02:54:28