Conor
Conor

Reputation: 740

Two one-to-many relationships in Ruby-On-Rails

I have 2 models within Rails, each path has a To field and a From field, both of which reference Location Id but I can't seem to get the relationships set up properly. Any help would be appreciated. I am using Rails 4.2.6.

class Location < ActiveRecord::Base
    #Fields - id, name, description, latitude, longitude

end

and

class Path < ActiveRecord::Base
    #Fields - id, from, to, distance

    # belongs_to :from_location, class_name: 'Location', foreign_key: 'from'
    # belongs_to :to_location, class_name: 'Location', foreign_key: 'to'

    # belongs_to :from_location, class_name: 'Location'
    # belongs_to :to_location, class_name: 'Location'
end

Upvotes: 1

Views: 79

Answers (1)

Sam Farmer
Sam Farmer

Reputation: 176

Assuming your 'from' and 'to' fields are integers that hold location ids, you should be able to do the following:

class Path < ActiveRecord::Base
  belongs_to :from_location, class_name: 'Location', foreign_key: 'from'
  belongs_to :to_location, class_name: 'Location', foreign_key: 'to'
end

Then for a Path record, you should be able to call .from_location and .to_location to get the Locations.

Have a read of this for more information.

Upvotes: 2

Related Questions