同时继承ActiveRecord

Inheritance with ActiveRecord at the same time

我有一个 class 'Report',其中包含 'description'、'pending' 等列

/app/models/report.rb
class Report < ActiveRecord::Base
end


class CreateReports < ActiveRecord::Migration
  def change
    create_table :reports do |t|
      t.boolean :pending, :default => true
      t.boolean :accepted, :default => false
      t.text :description
      t.timestamps null: false
    end
  end
end

但我还有另外两个 classes:ReportPost(当用户报告 Post 时)和 ReportTopic(当用户报告主题时)。我使用这种方法是因为我可以为 ReportTopic 使用 'belongs_to :topic',为 ReportPost 使用 'belongs_to :post'。那么,问题来了:

由于ReportPost和ReportTopic有相同的列'Report',我需要使用继承自'Report'。但我还需要使用 ActiveRecord 继承从 :report_topic migrates.

中捕获新属性

但是,怎么办?

这是其他 classes:

class ReportTopic < Report
  belongs_to :topic
end


class ReportPost < Report
  belongs_to :post
end

`并且,迁移:

class CreateReportPosts < ActiveRecord::Migration
  def change
    create_table :report_posts do |t|
      t.belongs_to :post

      t.timestamps null: false
    end
  end
end


class CreateReportTopics < ActiveRecord::Migration
  def change
    create_table :report_topics do |t|
      t.belongs_to :topic

      t.timestamps null: false
    end
  end
end

在这种情况下,您可以使用单一 Table 继承 (STI)。只需将名为 'type' 的列添加到您的报告 table.

  def change
    create_table :reports do |t|
      t.boolean :pending, :default => true
      t.boolean :accepted, :default => false
      t.text :description
      t.string :type
      t.timestamps null: false
    end
  end

Rails 会将此理解为 STI。您创建的任何子 class 的类型都将等于 class 的名称(例如 type = 'ReportTopic')