简体   繁体   中英

Rails Multi Table Inheritance and Polymorphic Associations

I'm currently developing an application using Rails 3.2 and have run into a bit of a problem. I know this has been asked hundreds of times before but I couldn't find an answer that solved it. Here is a similar ER: http://i.stack.imgur.com/x5V0G.png

Fairly obvious what i'm trying to do. I'm hoping for the association to read like the following:

Supplier.first.theatres.first.events.first.orders
TourEvent.first.orders
Tour.first.orders

Now it would be nice to be able to define my models like so:

class Event < ActiveRecord::Base
  has_many :orders
  belongs_to :eventable, polymorphic: true

  # id, eventable_id, eventable_type, title, date, price
end

class TourEvent < Event
  belongs_to :tour

  # id, tour_id, rendezvous, guide_name
end

class Tour < ActiveRecord::Base
   has_many :events, class_name: 'TourEvent'

  # id, name, venue, duration
end

But I understand that's reserved for "STI" rather than "MTI". Any ideas how to get my solution working without the need for complicated mixins or plugins? Or is it just not possible?

I think you can make something like this:

suppliers 
has_many :events

events
belongs_to :suppliers
belongs_to :institutions
has_many :orders
# id, supplier_id, institution_id, ...

institutions
# id, type, title, ...
types: theatre, club, tour

orders
belongs_to :events
# id, event_id

Then, you can access to event orders:

Supplier.first.events.first.orders

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM