I working in Rails 3 Activerecord. I have two models City and Shipment and I’m trying to model a shipment leaving from one city (ship_from) and shipping to another (ship_to). This is what I have:
class Shipment < ActiveRecord::Base
belongs_to :ship_from, :class_name => "City", :foreign_key => "city_id"
belongs_to :ship_to, :class_name => "City", :foreign_key => "city_id"
end
class City < ActiveRecord::Base
has_many :ship_froms
has_many :ship_tos
end
I know I missing something very simple and obvious, but I’m just not getting it. Any guidance would be greatly appreciated. Thanks.
You’re modeling two one-to-many relations. You’re saying as Shipment has one
fromcity and onetocity.The one side is the part that’s saved in your table. So you’re saving a
from_city_idand ato_city_idin your shipments table. Both these columns contain the id of a City.You model this one city relation by adding the following code in the Shipment class:
This code means we have a property
from_citywhich type isCity(from option :class_name, default would be FromCity). You can find the City by searching the table cities forid = from_city_id(id is the default for the option :primary_key, :from_city_id is the default for :foreign_key).For the to_city you declare
belongs_to :to_city, :class_name => ‘City’
The many part of the relation is in the
Cityclass. To say you have many Shipments from this city. You declare the following:The code means we have a property
from_shipmentswhich type is a collection ofShipments (:class_name). You can find the Shipment by searching in the table shipments forfrom_city_id = id(we override the default city_id by declaring a :foreign_key)For the to_city you declare
More info about the defaults and options for belongs_to, has_one, has_many can be found here.