它基于两个模型:公式和操作数。公式可以有很多操作数。每个操作数可以有很多或没有操作数。
我建立了一个多态关联,其中操作数属于操作,并且还有许多操作数作为运算符。公式有许多操作数作为操作本身。
我正在尝试构建一个可以处理此问题的nested_form,但是我被卡住了。我正在使用simple_nested_form。任何帮助将不胜感激。
class Formula < ActiveRecord::Base
validates_presence_of :name, :client_id
belongs_to :client
has_many :operands, as: :operation, dependent: :destroy
accepts_nested_attributes_for :operands, allow_destroy: true
end
class Operand < ActiveRecord::Base
validates_presence_of :operator
belongs_to :operation, polymorphic: true
has_many :operands, as: :operation, dependent: :destroy
accepts_nested_attributes_for :operands, allow_destroy: true
OPERATOR_TYPES = ["+", "-", "*", "/"]
end
更新
基于上面的模型,我添加了formula_controller:
def new
@formula.operands.build
end
在公式_form中,我添加了fields_for:operands
= simple_nested_form_for @formula, :html => { :class => 'form-vertical' } do |f|
= f.error_notification
.form-inputs
.row
.span3= f.input :name
.well
= f.fields_for :operands
= f.link_to_add t('helpers.links.add'), :operands
然后,部分_operands_fields,也渲染fields_for:operands
.well
.row
.span2= f.input :operator, collection: Operand::OPERATOR_TYPES
.span3= f.input :numeric_operand
.span3= f.link_to_remove t('helpers.links.remove')
.well
= f.fields_for :operands
= f.link_to_add t('helpers.links.add'), :operands
我认为这应该有效,但似乎在呈现公式表单时,它包含了字段_对于公式操作数。然后,在这部分内部,而不是包括“添加”,它呈现另一个操作数字段,依此类推,以无限循环结束,如下所示:
User Load (0.4ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 ORDER BY "users"."id" ASC LIMIT 1
Client Load (0.2ms) SELECT "clients".* FROM "clients" WHERE "clients"."id" = ? LIMIT 1 [["id", 1]]
Rendered formulas/_operand_fields.html.haml (48.4ms)
Rendered formulas/_operand_fields.html.haml (9.0ms)
Rendered formulas/_operand_fields.html.haml (7.5ms)
Rendered formulas/_operand_fields.html.haml (9.1ms)
Rendered formulas/_operand_fields.html.haml (8.8ms)
Rendered formulas/_operand_fields.html.haml (9.2ms)
Rendered formulas/_operand_fields.html.haml (9.3ms)
Rendered formulas/_operand_fields.html.haml (9.5ms)
Rendered formulas/_operand_fields.html.haml (17.7ms)
Rendered formulas/_operand_fields.html.haml (52.4ms)
Rendered formulas/_operand_fields.html.haml (10.4ms)
Rendered formulas/_operand_fields.html.haml (11.3ms)
如何解决这个问题?