Has_many through in Rails while assigning different roles

前端 未结 1 976
野性不改
野性不改 2021-01-22 14:50

I\'m trying to create a relationship between addresses and trips, and I\'m not sure exactly how to set up the relationship.

Each trip will have two addresses: the start

1条回答
  •  温柔的废话
    2021-01-22 15:42

    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.

    0 讨论(0)
提交回复
热议问题