【问题标题】:Inheritance with ActiveRecord at the same time同时继承ActiveRecord
【发布时间】: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


    【解决方案1】:

    在这种情况下,您可以使用单表继承 (STI)。只需将名为“类型”的列添加到您的报告表中即可。

      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。您可以创建的任何子类的类型都将等于类的名称(例如 type = 'ReportTopic')

    【讨论】:

    • 我已经尝试过这种方法。问题是:如何将“post_id”列直接(且仅)添加到“ReportPost”模型,将“topic_id”列添加到“ReportTopic”模型?
    • 嗯。您可以做的是在报告表中与这两个模型(帖子和主题)建立多态关联。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-13
    • 1970-01-01
    • 2012-10-13
    • 1970-01-01
    相关资源
    最近更新 更多