2012-05-14 102 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