[英]Polymorphic association in Rails 3
I've Googled and searched the forums but can't seem to find an answer that fits my scenario. 我已经在Google搜索并搜索了论坛,但似乎找不到适合我的情况的答案。
Let's say have the following models: 假设有以下模型:
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
Now I have another model called question. 现在,我有另一个模型称为问题。 It has a field named question_type_id that indicates what type of question it is and a field named question_id that is the foreign key to one of the askables.. I want to do something like this:
它具有一个名为question_type_id的字段,该字段指示问题的类型,以及一个名为question_id的字段,该字段是其中一个可问问题的外键。.我想执行以下操作:
class Question < ActiveRecord::Base
has_one :askable, :foreign_key => 'question_id' ....
end
and give it the correct askable but I'm not sure how to write the association. 并给出正确的要求,但我不确定如何编写关联。 Am I looking at this right or should I be trying to achieve this another way?
我是在看这种权利,还是应该尝试以其他方式实现这一目标?
Any help is appreciated! 任何帮助表示赞赏!
You should have your association the other way round 你应该反过来联系
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.