Rails 嵌套创建 STI

Rails Nested create STI

我有 4 个课程,实例上有一个 STI。

工作区、项目、任务、实例,(type1 <实例)和(type2 <实例)。

有适当的联想。 (工作区 has_many 个项目,has_many 个项目中的任务,依此类推)

我有这个嵌套创建(在实施 STI 之前工作):

if (%w(type1 type2).include?(params[:type]))

 sti_class = params[:type].classify.constantize

 workspaces.find_by_name(name: w_name). 
 projects.where( name: p_name).first_or_create!.
 tasks.where(name: t_name).first_or_create!.
 sti_class.create() 

现在,那行不通,我想不出办法。

然而,下面的工作,但我想保留嵌套创建。

task=  workspaces.find_by_name(name: w_name). 
        projects.where( name: p_name).first_or_create!.
        tasks.where(name: t_name).first_or_create!

sti_class.create(task_id: task.id) 

如何保留嵌套的创建?

我可以立即推断出的问题是 sti_class 方法未在您的 Task 模型中定义,因为您将其添加到方法链中。

不要真的认为您遵循了此处的最佳做法,但要立即解决问题,您可能应该执行以下操作:

if (%w(type1 type2).include?(params[:type]))
 # depending on the association between the type(s) and the tasks, 
 # you'd need to either singularize or pluralize here, I'd assume 
 # task has many types, therefore pluralize

 sti_class = params[:type].pluralize

 # if you're already calling `find_by_name`, you don't need to pass 
 # the name option here anymore, but the name argument

 workspaces.find_by_name(w_name). 
 projects.where(name: p_name).first_or_create!.
 tasks.where(name: t_name).first_or_create!.
 send(sti_class).create