2012-05-14 73 views
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”?

回答

0

原因是你实际上没有使用多态,你正在使用STI(Single Table Inheritance)。您正在定义和设置两者,但仅使用 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 

现在它会按照您的想法工作。

+0

谢谢,马林!它工作正常!很好,谢谢你对这个问题的解释 – wolfer