问题
I'm trying to accomplish the following with ruby on rails, and I have problems to get the model-configuration right:
I would like to model possible connections between airports. I created the following models:
> rails generate model airport city name
> rails generate model connection airport_id destination_id
But most of the n:m association examples deal with associations between two different models on the one hand, or self-referencing models on the other hand, but I want to model a n:m association of models in one table between each other.
I would like to do something like that:
ny = Airport.create({"city" => "New York"})
la = Airport.create({"city" => "Los Angeles"})
ny.destinations << la
la.destinations << ny
I could not find any example on how to do this.
Does anyone have an idea how to accomplish something like that with active record?
The following article from railscasts seems to help: http://railscasts.com/episodes/163-self-referential-association
app/models/airport.rb
class Airport < ActiveRecord::Base
attr_accessible :city, :name
has_many :connections
has_many :destinations, :through => :connections
has_many :inverse_connections, :class_name => "Connection", :foreign_key => "destination_id"
has_many :inverse_destinations, :through => :inverse_connections, :source => :airport
end
app/models/connection.rb
class Connection < ActiveRecord::Base
attr_accessible :airport_id, :destination_id
belongs_to :airport
belongs_to :destination, :class_name => "Airport"
end
Why is it called "inverse_"? Do you think thats the best solution to the problem or could you think of a better solution? What about performance / index?
best regards Andreas
来源:https://stackoverflow.com/questions/16388623/nm-self-join-with-ruby-on-rails-active-record