Has_many through in Rails while assigning different roles

一世执手 提交于 2019-12-02 01:23:50

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!