【发布时间】:2015-01-31 14:29:24
【问题描述】:
我有一个“报告”类,其中包含“描述”、“待定”等列。
/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
但我还有另外两个类:ReportPost(当用户报告帖子时)和 ReportTopic(当用户报告主题时)。我使用这种方法是因为我可以为 ReportTopic 使用 'belongs_to :topic' 和为 ReportPost 使用 'belongs_to :post'。那么问题来了:
由于 ReportPost 和 ReportTopic 具有相同的“报告”列,我需要使用“报告”的继承。但我还需要使用 ActiveRecord 继承从 :report_topic migrates 中捕获新属性。
但是,怎么做?
以下是其他类:
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
【问题讨论】:
标签: ruby-on-rails inheritance activerecord