2013-02-15 168 views
0

Rails 3.2.12和Ruby 1.9.3和Haml計算嵌套窗體上的屬性?

我想使用屬性的計數來控制'link_to'remove''的顯示,但我在設置邏輯時遇到問題。

以下是我的表單一些代碼,因爲它是目前:

.field 
     = codeline.label :name, "Units Alloc" 
     %br/ 
     = codeline.text_field :units_alloc, :precision => 6, :scale => 2, :size => 10, 
     :class => "ui-state-default" 
     = codeline.hidden_field :_destroy 
     = link_to "remove", '#', class: "remove_fields" 

這個作品很好,但我有「刪除」鏈接顯示出來,我會喜歡它,只顯示如果有兩個:units_alloc屬性。

這是我的嘗試:

.field 
     = codeline.label :name, "Units Alloc" 
     %br/ 
     = codeline.text_field :units_alloc, :precision => 6, :scale => 2, :size => 10, 
     :class => "ui-state-default" 
     - if :units_alloc.count > 1 
     = codeline.hidden_field :_destroy 
     = link_to "remove", '#', class: "remove_fields" 

,這裏是我的錯誤:

 NoMethodError in Contracts#new 

     Showing /home/tom/rails_projects/tracking/app/views/contracts 
     /_codeline_fields.html.haml where line #9 raised: 

     undefined method `count' for :units_alloc:Symbol 

,如果我的說法,而不是符號使用units_alloc,我還得到一個錯誤:

 NameError in Contracts#new 

     Showing /home/tom/rails_projects/tracking/app/views/contracts 
     /_codeline_fields.html.haml where line #9 raised: 

     undefined local variable or method `units_alloc' for 
     #<#<Class:0xadbde90>:0xa8956e8> 

我試圖使用'codeline.units_alloc',但這不起作用,同樣的錯誤被標記。

任何建議,或指點,以幫助我解決這個問題?

謝謝。

解決方案:由於斯科特小

應用程序/控制器/ contracts_controller.rb

def New 
    @show_remove = false 
    .... 
    .... 
    end 

應用程序/視圖/合同/ _codelines_fields.html.haml

.field 
     = codeline.label :name, "Units Alloc" 
     %br/ 
     = codeline.text_field :units_alloc, :precision => 6, :scale => 2, :size => 10, 
     :class => "ui-state-default" 
     - if @show_remove 
      = codeline.hidden_field :_destroy 
      = link_to "remove", '#', class: "remove_fields" 
     - else 
     - @show_remove = true 

這做了它......刪除按鈕只顯示在第二行和後續的屬性。

+0

感謝James Scott Jr提供的解決方案: – thomasvermaak 2013-02-21 23:06:52

回答

1

當你處於表單(部分)時,codeline不會引用表單(部分)適用於Codeline實例的實例,而是一個ActionView :: Helpers :: FormBuilder實例那簡單的知道如何將信息與Codeline的實例相關聯。你知道,因爲在部分的第一行,你有codeline.object.build_code

因此,如果你想訪問關於units_alloc的信息,你可以用codeline.object.units_alloc來訪問它們。這會爲你提供你的條件數據。

1

我只想補充一點,如果您的定位標記的目的是使用一些javacscript從表單列表中刪除元素,那麼您可能會使用錯誤的控件。錨標籤不是表單元素,它們應該指向資源/內容,並且不能用作動畫/客戶端行爲觸發器。根據你描述的用例,一個輸入標籤類型=按鈕對於你似乎試圖實現的東西來說將是一個更加適合的元素。

+0

謝謝@ChuckE ...我將不得不激發灰色細胞來欣賞這裏的細微差別...有些研究我會更加讚賞您的觀點。 – thomasvermaak 2013-03-30 21:02:31

+0

現在才注意到編輯器沒有考慮到我的html標籤。我的意思是輸入標籤,類型=按鈕 – ChuckE 2013-03-30 22:34:53