In rails this is normally done with a condition on the association. You can use it in combination with "has_one through". Create a new model, let's call it TripLocation
which would be the mapping table between trips and addresses. In it you would have the column, say "destination". If the column is true, this mapping is for a destination address.
So let's say the migration looks like this:
create_table :trip_locations do |t|
t.belongs_to :trip
t.belongs_to :address
t.boolean :destination
end
And these would be the models:
class TripLocation < ActiveRecord::Base
belongs_to :trip
belongs_to :address
end
class Trip < ActiveRecord::Base
has_one :origin_trip_location,
class_name: 'TripLocation',
conditions: { destination: nil }
has_one :destination_trip_location,
class_name: 'TripLocation',
conditions: { destination: true }
has_one :origin, through: origin_trip_location, source: :trip
has_one :destination, through: destination_trip_location, source: :trip
end
So because of the conditions set on the "through" associations, calling @trip.origin
and @trip.destination
should give you the correct addresses.
When it comes to designating addresses as origin or destination, you can simply assign an address to whichever you need. @trip.origin = Address.first
, or @trip.destination = Address.second
, and I believe it should do the right thing with setting the destination flag. Try it.