2013-05-13 13 views
2

我試圖拒絕一個空的表單條目,但我有困難。我如何使用除了嵌套散列中的拒絕

用戶既可以選擇現有位置,也可以創建一個新位置。我希望表單實際顯示空白字段,但是當它們全部爲空時拒絕它們。由於'_destroy'永遠不會是空的,我需要做個例外。如果只填寫數量,則可以拒絕該條目。

表單提交下列資料:

參數:

{"product"=> 
     {..., 
     "product_locations_attributes"=> 
      { 
      "0"=>{"location_attributes"=>{"_destroy"=>"false", "street"=>"", "number"=>"", "zipcode"=>"", "city"=>"", "country"=>""}, "quantity"=>""}, 
      "1"=>{"_destroy"=>"false", "location_id"=>"", "quantity"=>""}} 
      } 
     , "commit"=>"Create Product" 
     } 

A我試圖讓空位置在產品模型中移除如下:

accepts_nested_attributes_for :product_locations, :allow_destroy => true, 
    :reject_if => proc {|a| a.except('_destroy', 'quantity').values.all?(&:blank?)} 

因爲它是嵌套的,它不會像這樣工作。 那麼如何檢查除數量和_destroy之外的所有物品是否空白? 應該可以一次完成它嗎? 感謝您的幫助。

*更新,以使其更清晰*

+0

數據,就像你寫的那樣,是一個'Array'。你的意思是提供一個'哈希'? – rossta 2013-05-13 12:21:57

+0

嗯,好點。也許我需要更好地瞭解我想要做的事情。 – Fritzz 2013-05-13 12:33:07

+0

@Fritzz在'proc'中,是'a'那個數組? – Stefan 2013-05-13 12:38:54

回答

0

感謝@RobHeaton的服務員,我終於完成了這項工作。 Myabe他的回答可以工作,但它對我沒有用。如果它應該和我做錯了,讓我知道,我會接受他的答案。我終於得到它與下面的代碼工作:

accepts_nested_attributes_for :product_locations, :allow_destroy => true, :reject_if => :empty_fields 

    def empty_fields(a) 
    if la = a[:location_attributes] 
     la[:street].blank? && la[:number].blank? && la[:city].blank? && la[:zipcode].blank? && la[:country].blank? 
    else 
     a[:location_id].blank? 
    end 
    end 

它現在很清楚什麼需要是空白,以便它拒絕。我嘗試過其他的事情,結果是接受或拒絕了太多的事情。 只要寫下來以防其他人遇到同樣的問題。

0

我會明確地檢查可能會或可能不會是空白的,而不是試圖做一些的各個領域「是他們都空白」。更加明確和可讀。

:reject_if => proc {|a| 
    location_attributes = a[:location_attributes] 
    a[:street].blank? && a[:number].blank? && a[:location_id].blank? 
} 

從長遠來看,它會變得冗長但更好!

+0

感謝您的回答。我希望將一個.except作爲一個更靈活的解決方案,以防將新字段添加到地址中,但是,好吧,我喜歡你的論據,因爲它更加冗長和可讀。 問題在於,在此解決方案中,使用現有位置的新product_locations(原始問題中的product_location [1]),現在也由於未找到location_attributes而被拒絕。至少這就是我現在看到的,我正在嘗試你的解決方案..或者是其他的錯誤? – Fritzz 2013-05-15 07:08:06

+0

沒問題 - 在這種情況下,傳入proc的屬性哈希是什麼樣的? – RobHeaton 2013-05-15 08:36:27

+0

屬性散列具有使用一個新的位置,或一個現有的,象這樣product_locations: 「產品」=> { 「product_locations_attributes」=> { \t \t \t 「1」=> \t \t \t \t { 「location_attributes」=> \t \t \t \t \t { 「_destroy」=> 「假」, 「街道」=> 「Esmoreitstraat」, 「數量」=> 「60」, 「郵政編碼」=> 「1017 DT」, 「city」=>「阿姆斯特丹」,「國家」=>「荷蘭」},「數量」=>「3」}, \t \t \t 「2」=> \t \t \t \t { 「_destroy」=> 「假」, 「LOCATION_ID」=> 「1」, 「數量」=> 「」, 「ID」=> 「110」}, \t \t \t 「3」=> \t \t \t \t { 「_destroy」=> 「假」, 「LOCATION_ID」=> 「」, 「數量」=> 「3」} \t \t \t} 「提交「=>」創建產品「 } 1是新的,2是存在的,3是無效的。 – Fritzz 2013-05-15 09:09:39