带有Cocoon的Rails 5.0:嵌套字段中的belongs_to问题

时间:2017-09-05 09:15:17

标签: ruby-on-rails belongs-to apache-cocoon

我有三个型号:

模型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-name就会覆盖第一个G-name。 使用firebug检查表单我可以看到第二个G名称缺少随机ID,因此错误变得清晰。 任何帮助表示赞赏......!

1 个答案:

答案 0 :(得分:1)

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

从评论中我了解到每个SequenceVariation都有一个Gene,但是当添加 new SequenceVariation时,没有Gene可见。我们可以为基因添加link_to_add_association,或假设每个序列变异必须有一个基因,预构建一个基因。我们可以使用wrap_object的{​​{1}}选项执行此操作:

link_to_add_association

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

然后= link_to_add_association('add sequence variation', f, :svs, wrap_object: Proc.new {|sv| sv.build_gene; sv }) 部分可以按如下方式进行调整:

sv_fields