如何设置嵌套已多次关系以访问祖父模型上的深层嵌套数据?

时间:2016-01-23 18:09:09

标签: ruby-on-rails ruby has-many-through

我有抽奖券,抽奖券和买票的人。我想做的是(从抽奖活动中),看看谁买了门票。

简而言之:抽奖有很多门票。门票有很多买家。

如何实现这种代理/聚合/扁平化有很多有很多?

1 个答案:

答案 0 :(得分:0)

这有点棘手,因为您需要指定源类和源关联,具体取决于您正在设置的关系的哪个端口。

请参阅:

class Raffle < ActiveRecord::Base
  has_many :raffle_tickets,
    class_name: LineItem::RaffleTicket.name,
    foreign_key: 'reference_id'

  has_many :ticket_purchasers,
    class_name: Buyer.name,
    through: :raffle_tickets,
    source: :purchasers
end

class LineItem::RaffleTicket < LineItem
  belongs_to :raffle, foreign_key: :reference_id

  # has_many :buyer_line_items # defined in LineItem
  has_many :purchasers,
    through: :buyer_line_items,
    source: :buyer
end

class BuyerLineItem < ActiveRecord::Base
  belongs_to :buyer
  belongs_to :line_item # polymorphic
end

这将允许您执行以下操作:

purchasers = Raffle.first.ticket_purchasers
purchasers.map(&:class)
=> [Buyer, Buyer, Buyer, etc...]

以上相当于在抽奖模型上定义以下方法:

def ticket_purchasers
  raffle_tickets.map(&:purchasers).flatten
end