Ruby on rail发票表上的多种产品可能性

时间:2017-05-16 09:41:38

标签: sql ruby-on-rails ruby

我目前在网络市场上有4张桌子。

Table User: Username + password + email.
Table Serie: Serie name + price + description
Table Season: Season name + price + description + fk(Serie)   //Each season belongs to a serie 
Table Chapter: Chapter name + price + description + fk(Season)   //Each chapter belongs to a season

用户可以购买系列季节和章节。主要想法如下:

Table invoice: fk(user)   //User have multiple invoices
Table invoice_line: fk(invoice), fk(serie|season|chapter)   //Each invoice contains multiple products

我怎样才能轻易代表该系列关系?

1 个答案:

答案 0 :(得分:1)

您可以使用Active Record中的polymorphic association

它可以表示如下:

class InvoiceLine < ActiveRecord::Base
  belongs_to :invoice
  belongs_to :containable, polymorphic: true
end

使用这个定义你应该有这样的表:

create_table :invoice_lines do |t|
  t.references :invoice,
  t.references :containable, polymorphic: true
end

t.references :containable, polymorphic: true将创建整数containsable_id和string containsable_type列。