Rails中的多态关联3

时间:2013-06-06 16:58:34

标签: ruby-on-rails polymorphic-associations

我用Google搜索并搜索了论坛,但似乎无法找到适合我情景的答案。

假设有以下型号:

class TextProblem < ActiveRecord::Base
   belongs_to :askable, :polymorphic => true
   ...
end

class MultipleChoice < ActiveRecord::Base
   belongs_to :askable, :polymorphic => true
   ...
end

class WordMatch < ActiveRecord::Base
  belongs_to :askable, :polymorphic => true
  ...
end

现在我有另一个名为问题的模型。它有一个名为question_type_id的字段,表示它是什么类型的问题,还有一个名为question_id的字段,它是其中一个问题的外键。我想做这样的事情:

class Question < ActiveRecord::Base
    has_one :askable, :foreign_key => 'question_id' ....  
end

并给它正确的问题,但我不知道如何写关联。我正在看这个问题,还是我应该尝试另一种方式?

感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

你应该让你的协会反过来

class Question < ActiveRecord::Base
    belongs_to :askable, :polymorphic => true 
end

class TextProblem < ActiveRecord::Base
   has_many :questions, :as => :askable
   ...
end

class MultipleChoice < ActiveRecord::Base
   has_many :questions, :as => :askable
   ...
end

class WordMatch < ActiveRecord::Base
 has_many :questions, :as => :askable
  ...
end

请参阅this