Rails 5.0 with Cocoon:嵌套字段内的 belongs_to 问题

Rails 5.0 with Cocoon: Issue with belongs_to inside of nested fields

我有三个模型:

模型 P

has_many :svs
has_many :gs, through: svs
accepts_nested_attributes_for :svs

模型 SV

belongs_to :p
belongs_to :g
accepts_nested_attributes_for :g

G 型

has_many :svs
has_many :ps, through: svs

我需要的是一个 P 的表格,其中包含一个或多个 SV 的嵌套表格,并且这些 SV 表格中的每一个都必须有另一个嵌套表格,正好是一个 G(苗条):

= form_for @p do |p|
        ...
        ...
        = render 'sv_form', f: p
    = p.submit

sv_form

= f.fields_for :svs do |sv|
    `= sv.fields_for :g do |g|`
        ...
        ...
        #sv
            = render 'sv_fields', f: sv, g: g
    .links
        = link_to_add_association 'add sv', f, :svs, partial: 'sv_fields', render_options: {locals: {g: g}}

sv_fields

.nested_fields
    = g.label :name # here is the problem: no random id for these fields
    = g.text_field :name # here also no random id
    = f.label :name
    = f.text_field :name
    ...
    ...
    = link_to_remove_association 'remove SV', f

只要我只用一个SV保存P就可以正常工作。 但是一旦我添加第二个 SV,第二个 SV 的 G 名称就会覆盖第一个 G 名称。 使用 firebug 检查表单,我可以看到第二个 G 名称缺少随机 ID,因此错误变得清晰。 任何帮助表示赞赏...!

[为了便于阅读,我假设 P=Patient,SV=SequenceVariation,G=Gene]

从评论中我了解到每个 SequenceVariation 都有一个 Gene,但是当添加 new SequenceVariation 时,看不到任何 Gene。我们可以为一个基因添加一个 link_to_add_association,或者假设每个序列变异都必须有一个基因,预先构建一个基因来填充。我们可以使用 link_to_add_associationwrap_object 选项来做到这一点:

= link_to_add_association('add sequence variation', f, :svs, wrap_object: Proc.new {|sv| sv.build_gene; sv })

这将确保每个新的序列变异也将有一个初始化的基因。

然后 sv_fields 部分可以调整如下:

.nested_fields
  = f.label :name 
  = f.text_field :name
  = fields_for :gene do |g|
    = g.label :name
    = g.text_field :name
  = link_to_remove_association 'remove SV', f