2017-01-10 27 views
0

我有一個家長對象,有幾十個孩子,都非常相似。我有一張表格和一張表格,用繭編輯它們。有了它(和this answer),我可以添加新行到表中,並刪除現有的,它工作得很好。如何使用cocoon在Rails中克隆子對象?

我想要做的是在行尾添加另一個按鈕,以便與刪除按鈕一起使用,將該行克隆爲新行。

父窗體:

= simple_form_for @release, html: { multipart: true } do |f| 
    = f.error_notification 
    .col-md-12 
    %table#myTable.table-striped.table-bordered 
     %thead 
     %tr 
      %th Description 
      ... 
      %th Remove 

     %tbody.codes 
     = f.simple_fields_for :codes, wrapper: false do |code| 
      = render 'code_fields', f: code 
      ---> New code below would go here <--- 

    .links 
     = link_to_add_association 'Add Code', f, :codes, data: {"association-insertion-node" => "tbody.codes", "association-insertion-method" => "append"} 

    .form-actions 
     = f.button :submit, class: 'btn btn-primary pull-right' 

兒童部分:

%tr.nested-fields 
    = f.input :id, as: :hidden 
    %td= f.input :description, label: false, input_html: { class: 'input-sm myinput' } 
    ... 
    %td 
    = link_to_remove_association f, class: 'btn btn-default btn-xs' do 
     .glyphicon.glyphicon-remove 

我希望能夠像這樣添加一些行的最後td元素:

= link_to_add_association 'Clone', f, :codes, data: {"association-insertion-node" => "tbody.codes", "association-insertion-method" => "append"}, render_options: {locals: {code: code.object}} 

我有2個問題。首先,繭預先生成要插入的HTML的方式,我不能將該函數調用放在部分內容中,因爲 - 即使我想要正確地使用語法 - 它會創建一個無限循環。

我很樂意通過某種方式解決這個問題,如果有某種方法可以將DOM節點「植入」HTML值,那麼jQuery將DOM節點置於相應錶行的最後一個單元格中當前對象。在我想要插入「克隆」按鈕的位置,我在code.object變量中擁有當前的「代碼」子對象。 (至於code此時是fields_for表單對象。)

有沒有辦法做到這一點? render_options似乎很有前途,但我無法弄清楚這是否僅僅是一個語法問題,或者如果生成器永遠不會查看我在生成字段中傳遞的值的散列值。

回答

1

看看:wrap_object選項,它允許預先初始化對象,我認爲你應該也可以使用它從一個現有的對象克隆。

E.g.這樣的事情可能工作:

- code_to_clone = f.object 
= link_to_add_association('Clone', f, :codes, 
    wrap_object: Proc.new { |new_code| new_code.name = code_to_clone.name; new_code }) 

只複製用於演示目的:)

+0

'= link_to_add_association '克隆',F,1場:代碼,數據:{ 「協會插入節點」=>「 tbody.codes「,」association-insertion-method「=>」append「},wrap_object:Proc.new {| d | d = code.object.clone; d.id = nil; d}'有用! –

+0

剛剛發現我應該在新版Rails中使用#dup而不是#clone。 –