【问题标题】:Rails Multi Table Inheritance and Polymorphic AssociationsRails 多表继承和多态关联
【发布时间】:2012-02-29 11:17:52
【问题描述】:

我目前正在使用 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”保留的。任何想法如何让我的解决方案在不需要复杂的 mixin 或插件的情况下工作?还是根本不可能?

【问题讨论】:

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


    【解决方案1】:

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

    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
    

    【讨论】:

    • 对不起 - 我不认为你理解这个问题。我已经做了一些进一步的阅读,我相信我说目前在 Rails 3.2.1 中无法本地执行多表继承是对的(还没有!)。会是一个不错的补充。
    • 正如我在图片i.stack.imgur.com/x5V0G.png 中看到的那样,您想要存储数据库供应商、订单和事件。活动属于机构(如剧院或俱乐部)。为什么需要额外的表,例如 theather_events 或 club_events?为什么每个机构都需要表格?
    • 每个“机构”存储不同的信息。区分这一点对我来说很重要。
    • 您的机构表将是 STI。您可以为每种类型的机构创建模型。
    猜你喜欢
    • 2015-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-03
    • 1970-01-01
    • 1970-01-01
    • 2013-10-25
    相关资源
    最近更新 更多