0

我有

class Question < ActiveRecord::Base
   has_many :tasks, :as => :task
end

class QuestionPlayer < Question
end

class QuestionGame < Question
end

class Tast < ActiveRecord::Base
  belongs_to :task, :polymorphic => true
end

当我做

Task.create :task => QuestionPlayer.new
#<Task id: 81, ... task_id: 92, task_type: "Question">

为什么?如何使用 task_type = "QuestionPlayer" 获得任务?

4

1 回答 1

0

原因是您实际上并没有使用多态性,而是使用了 STI(单表继承)。您正在定义和设置两者,但仅使用STI。

外键的目的,即使是您定义的多态外键,也是为了引用数据库表中的另一条记录。活动记录必须存储主键和具有该记录的表名的类。这正是它正在做的事情。

也许您真正想做的是为每个 Question 对象使用具有不同类的 STI。在这种情况下,这样做,

class CreateQuestionsAndTasks < ActiveRecord::Migration
  def self.up
    create_table :questions do |table|
      table.string :type
    end
    create_table :tasks do |table|
      table.integer :question_id
    end
  end
end
class Question < ActiveRecord::Base
  has_many :tasks
end
class QuestionPlayer < Question
end
class QuestionGame < Question
end
class Task < ActiveRecord::Base
  belongs_to :question
end

现在它会像你想象的那样工作。

于 2012-05-14T10:24:36.367 回答