Ruby 在 rails 个表上

Ruby on rails tables Polymorphism

我正在尝试为包含连续剧、剧季和章节的用户生成订单。这些是我的模型:

class User < ApplicationRecord
   has_many :orders
end

class Order < ApplicationRecord
   has_many :lines
   has_many :products, through: :lines
end

class Line < ApplicationRecord
    belongs_to :order
    belongs_to :product (THIS CAN BE A SERIE,SEASON,CHAPTER)
end

我怎样才能做好这段关系?我必须在 Serie、Season、Chapter 表上放什么?

使用 polymorphic association

首先更新linestable:

class AddProductsToLines < ActiveRecord::Migration[5.0]
  def change
    edit_table :lines do |t|
      # ... other attributes
      t.references :product, polymorphic: true, index: true
    end
  end
end

其次,更新您的模型:

class Line < ApplicationRecord
  belongs_to :order
  belongs_to :product, polymorphic: true 
end

class Serie < ApplicationRecord
  has_many :lines, as: :product
end

class Season < ApplicationRecord
  has_many :lines, as: :product
end

class Chapter < ApplicationRecord
  has_many :lines, as: :product
end