如何使用 STI 创建与现有模型相关的新模型?

How do I create a new model, related to an existing model, using STI?

如果我有以下使用 STI 的型号:

# Organization Model
class Organization < ActiveRecord::Base
  has_many :questions
  has_many :answers, :through => :questions
end

# Base Question Model
class Question < ActiveRecord::Base
  belongs_to :organization
  has_many :answers
end

# Subclass of Question
class TextQuestion < Question

end

# Subclass of Question
class CheckboxQuestion < Question

end

构建特定类型 Question 也与 Organization 相关的新对象的正确方法是什么?或者换句话说,如果我有一个组织,并且我希望该组织有一个新的 CheckboxQuestion,我可以使用常规的构建器方法吗?

例如,我期望能够做到:

org = Organization.last
org.text_questions.build(:question_text => "What is your name?")

...但这给了我一个 NoMethodError: undefined method text_questions 错误。

在没有看到您的 Organization 模型的情况下不能 100% 确定,但这可能是您正在寻找的:

class Organization < ActiveRecord::Base
  has_many :test_questions
  has_many :checkbox_questions
end

希望对您有所帮助:)

Organization 模型不知道从 Question 继承的 classes,因此您可以 initiate/create 通过这种方式提问实例。为了 initiate/create 特定类型的问题,您必须自己明确设置。例如:

organization = Organization.where(...).last
organization.questions.build(question_text: 'text', type: 'TextQuestion')

您可以在 Organization class 处定义多个 has_many *_questions,但这感觉是一个糟糕的设计,如果您最终有很多 Question subclass 在你的申请中。