0

我已经用谷歌搜索并搜索了论坛,但似乎找不到适合我的情况的答案。

假设有以下模型:

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

并给出正确的问题,但我不确定如何编写关联。我是在看这个权利还是应该尝试以另一种方式实现这一目标?

任何帮助表示赞赏!

4

1 回答 1

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

参考这个

于 2013-06-06T17:13:54.943 回答