使用多态关联创建

时间:2012-05-14 10:08:11

标签: ruby-on-rails polymorphic-associations

我有

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”获取任务?

1 个答案:

答案 0 :(得分: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

现在它可以正常运作。