2014-02-17 38 views
0

我試圖做一個有時有額外的字段(嵌套模型),當做一個新的條目,但不會需要這些領域時執行更新的窗體之一。因此,我試圖通過一個塊傳遞額外的字段,但表單對象沒有正確傳遞。Rails 4產生額外的表單字段

有沒有辦法將表單對象(或任何變量)傳遞到yield?參考

示例代碼:

_form.slim

= nested_form_for @model do |f| 
    .row 
    = f.label :name 
    = f.text_field :name, autofocus: true 
    ... 
    = yield 
    ... 
    = f.submit 'Save' 

new.html.slim

== render layout: 'model/form' do 
    h3 Additional Fields 
    = f.fields_for :nested do |h| 
     = a.label :name, 'Nested Name' 
     = a.text_field :name 
     = a.link_to_remove do 
     = fa_icon 'times-circle-o' 
    = f.link_to_add "Add another nested model", :nested 

edit.html.slim

== render layout: 'model/form' 
+0

我有點困惑,你爲什麼要渲染布局_在你的意見?你不應該渲染partials嗎? –

+0

我開始嘗試使用partials開始,但它不工作,所以我試圖按照這篇文章:http://stackoverflow.com/questions/2951105/rails-render-partial-with-block –

+0

嗯,那個問題是4歲,我不確定這個問題是否會實際發揮作用。就個人而言,我只是使用partials,並傳入一個局部變量,如'additional_fields',然後以partial的形式做一個條件,並且只在'additional_fields'爲true時才顯示額外的字段。 –

回答

1

爲了詳細說明我的評論,這是我的方式它採用諧音:

_form.slim

= nested_form_for @model do |f| 
    .row 
    = f.label :name 
    = f.text_field :name, autofocus: true 

    ... 

    - if defined?(additional_fields) 
    h3 Additional Fields 
     = f.fields_for :nested do |h| 
      = a.label :name, 'Nested Name' 
      = a.text_field :name 
      = a.link_to_remove do 
      = fa_icon 'times-circle-o' 
     = f.link_to_add "Add another nested model", :nested 

    ... 

    = f.submit 'Save' 

new.html.slim

== render 'model/form', :additional_fields => true 

edit.html.slim

== render 'model/form' 

我可能會錯過一些東西,但我不確定爲什麼這樣做不起作用。