私は他の旅行者(他の旅行者)と関連させたいモデル(旅行)を持っています。同じモデルの2つのレコードをリンクするためのActiveRecord関係宣言? (自己参照の多対多)
2つの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