In my application, a city can have many links. A link connects two cities together and is bi-directional, so the link does not have a "from" and "to." This leads to the following db schema:
create_table "links", force: true do |t|
t.integer "endpoint1_id"
t.integer "endpoint2_id"
t.integer "capacity"
end
create_table "cities", force: true do |t|
t.string "name"
t.string "lat"
t.string "long"
end
In my ActiveRecord models, I want to declare a relationship between two tables. Since I cannot declare two foreign keys when setting up the relationship has_many, I worked on this as follows:
class City < ActiveRecord::Base
def links
Link.where("endpoint1_id=? OR links.endpoint2_id=?", id, id)
end
end
class Link < ActiveRecord::Base
belongs_to :endpoint1, :class_name => 'City'
belongs_to :endpoint2, :class_name => 'City'
end
This allows me to do: City.find(1).linksbut it does not seem to be the right solution and does not impose any inheritance. In addition, from linkI can not find a city of relations, if I do not go through city.endpoint1and city.endpoint2.
has_many ? - db schema?