我有 4 个分支,实例上有 STI。
工作区、项目、任务、实例(类型 1 <实例)和(类型><实例)。>
具有适当的关联。(工作区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