2014-10-19 71 views
0

我試圖在一個頁面內爲多個節使用表單部分。第一次,我通過「部分:」o「」,第二次通過「部分:」s「」。Ruby on Rails - 在傳遞兩個不同變量的同時傳遞部分兩次錯誤

它在我傳遞第一個變量時成功工作,但是第二次呈現表單部分時,它會生成一個「未定義的方法`人性化爲nil:NilClass」錯誤。

下面是的渲染追加的部分形式的一個例子:

<some form stuff here> 
<%= render partial: "item_form", locals: {f: f, section: "o"} %> 
<some form stuff here> 
<%= render partial: "item_form", locals: {f: f, section: "s"} %> 

這裏是一個的所呈現的_item_form.html.erb的一部分部分:

<% unless @item.paragraphs.empty? %> 
    <% @item.paragraphs.each do |paragraph| %> 
     <% field_type = "Paragraph" if paragraph.paragraph_type == "#{section}paragraph" %> 
     <% field_type = "Figure description" if paragraph.paragraph_type == "#{section}figure" %> 
     <% field_type = "Bullet" if paragraph.paragraph_type == "#{section}bullet" %> 
     <div class="form-group"> 
      <%= f.label field_type, class: "col-sm-2 control-label" %> 

,我得到的錯誤突出顯示了f.label行(上例中的最後一行),並將「nil:NilClass」的未定義方法`人性化'錯誤吐出。

任何想法這裏發生了什麼?如果我刪除第一個渲染,它仍然不起作用。如果我刪除第一個渲染並將第二個部分更改爲「o」而不是「s」,那麼它就可以工作。添加除了「o」以外的任何其他字母以將該部分擰緊。

回答

1

的field_type只在某些情況下定義,你可以在你的代碼中看到:

<% field_type = "Paragraph" if paragraph.paragraph_type == "#{section}paragraph" %> 
<% field_type = "Figure description" if paragraph.paragraph_type == "#{section}figure" %> 
<% field_type = "Bullet" if paragraph.paragraph_type == "#{section}bullet" %> 

你確定它們中的至少一個總是爲真?

我的猜測是,你的確有一個類型爲oparagraph,ofigure或obullet的段落,但不是類型sparagraph,sfigure或sbullet,所以最後你會得到一個零字段類型。

我不知道你的應用程序背後的商業邏輯,但我會建議定義一個標準的情況下(當然,如果你可以),然後在必要時更新,如:

<% field_type = "Paragraph" %> 
<% field_type = "Figure description" if paragraph.paragraph_type == "#{section}figure" %> 
<% field_type = "Bullet" if paragraph.paragraph_type == "#{section}bullet" %> 

我也會建議將此邏輯移至幫助程序,而不是在視圖本身中決定字段標籤名稱。

+0

啊,好的。我沒有發現它出於某種原因抱怨field_type。以爲這是在抱怨f。感謝您的建議。現在要走這條路。我想我可以根據你的幫助解決這個問題。再次感謝 – LewlSauce 2014-10-19 20:38:19

相關問題