I have Flight, Person, and Glider models in a Rails 3 application. I defined a user relationship because I need more than one foreign key referring to a Person from the flight table. Associations only work with ONE.
class Flight < ActiveRecord::Base belongs_to :pilot, :class_name => "Person" belongs_to :instructor, :class_name => "Person" belongs_to :towplane_pilot, :class_name => "Person" belongs_to :airplane_instructor, :class_name => "Person" belongs_to :glider belongs_to :rep_glider, :class_name => "Glider" belongs_to :departure_airfield, :class_name => "Airfield" belongs_to :arrival_airfield, :class_name => "Airfield" end class Glider < Aircraft has_many :flights has_many :replaced_flights, :foreign_key => "rep_glider_id", :class_name => "Flight" end class Person < ActiveRecord::Base has_many :flights, :foreign_key => "pilot_id", :class_name => "Flight" has_many :instructed_flights, :foreign_key => "instructor_id", :class_name => "Flight" has_many :towed_flights, :foreign_key => "towplane_pilot_id", :class_name => "Flight" has_many :instructed_towing_flights, :foreign_key => "airplane_instructor_id", :class_name => "Flight" end
I am almost there, but I do not understand how Glider.first.flights works when Person.first.flights does not work.
UPDATE: Associations with Airfield work ... so I donβt know why this does not work with Face
class Airfield < ActiveRecord::Base has_many :takeoff_flights, :foreign_key => "departure_airfield_id", :class_name => "Flight" has_many :grounded_flights, :foreign_key => "arrival_airfield_id", :class_name => "Flight" end ###Works Correctly Airfield.first.takeoff_flights Airfield.first.grounded_flights Flight.first.departure_airfield Flight.first.arrival_airfield
ruby-on-rails activerecord ruby-on-rails-3 foreign-key-relationship
bruno077
source share