Rails多表继承和多态关联

时间:2012-02-29 11:17:53

标签: ruby-on-rails ruby-on-rails-3 rails-models

我目前正在使用Rails 3.2开发一个应用程序,并遇到了一些问题。我知道之前已经问了好几百次,但我找不到解决问题的答案。以下是类似的ER:http://i.stack.imgur.com/x5V0G.png

我正在努力做的事情非常明显。我希望该协会的内容如下:

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

现在能够如此定义我的模型会很高兴:

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

但据我所知,这是为“STI”而不是“MTI”而保留的。任何想法如何让我的解决方案工作,而不需要复杂的mixins或插件?或者这是不可能的?

1 个答案:

答案 0 :(得分:0)

我认为你可以做这样的事情:

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

然后,您可以访问事件订单:

Supplier.first.events.first.orders