ActiveRecord relationship declarations for linking two records of the same model? (Self-referential many-to-many)
I have a model (Trip) that I want to have be related to others of its kind (other trips).
The join model is used that stores the two trip_id values and a strength value (representing the strength of the relationship).
What makes my situation tricky is that the relationship is a two-way relationship. So their is no "owner" of the relationship. I want to take @trip_a and ask for @trip_a.trip_relations to find all its related trips. And equally I want to ask for @trip_b.trip_relations.
Code might help explain:
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
The above doesn't work but hopefully helps illustrate the intent.
I want to be able to take any trip and ask for @trip.trip_relations and get a list of both @trip.trip_as and 开发者_JAVA技巧@trip.trip_bs (with duplicates removed).
I would also like to take any trip and set up a relationship like @trip_a.trip_relations << @trip_b. Now @trip_a.trip_relations.include?(@trip_b) #=> true and @trip_b.trip_relations.include?(@trip_b) #=> true.
I could write a custom methods but I wonder if there is a way to do this cleanly with ActiveRecord.
There is a library for dealing with mutual relationships called acts_as_network that I've used in the past for relationships that are similar to what I believe you're getting at:
https://github.com/sjlombardo/acts_as_network
精彩评论