2012-05-12 71 views
1

以下是給我的問題:如何在ruby/rails中將多個參數傳遞給Proc?

accepts_nested_attributes_for :photo, 
:reject_if => proc { |attributes| attributes['image'].blank? }, 
:reject_if => proc { |attributes| attributes['photo_title'].blank? }, 
:allow_destroy => true 

我想這是因爲我打電話:reject_if兩次,不是100%肯定。但是,當我取消註釋photo_title reject_if行時,如果我選擇了一個,我的圖像將無法上傳。如果我評論這條線,那麼它就是。

如何將兩個條件合併爲一個reject_if條件?如果這是有道理的。

親切的問候

+1

爲什麼不使用extern方法來清理處理邏輯? – apneadiving

回答

5

此:

accepts_nested_attributes_for :photo, 
    :reject_if => proc { |attributes| attributes['image'].blank? }, 
    :reject_if => proc { |attributes| attributes['photo_title'].blank? }, 
    :allow_destroy => true 

是一樣的:

accepts_nested_attributes_for :photo, { 
    :reject_if => proc { |attributes| attributes['image'].blank? }, 
    :reject_if => proc { |attributes| attributes['photo_title'].blank? }, 
    :allow_destroy => true 
} 

脂肪箭頭論點實際上是一個哈希,大括號是必不可少的由Ruby背後加上。 A散列不允許重複鍵,以便第二:reject_if值覆蓋第一個和你結束了這一點:

accepts_nested_attributes_for :photo, 
    :reject_if => proc { |attributes| attributes['photo_title'].blank? }, 
    :allow_destroy => true 

您可以在一個PROC雖然合併兩個條件:

accepts_nested_attributes_for :photo, 
    :reject_if => proc { |attributes| attributes['image'].blank? || attributes['photo_title'].blank? }, 
    :allow_destroy => true 

你可以也使用單獨的方法:

accepts_nested_attributes_for :photo, 
    :reject_if => :not_all_there, 
    :allow_destroy => true 

def not_all_there(attributes) 
    attributes['image'].blank? || attributes['photo_title'].blank? 
end 
1

試試這個

accepts_nested_attributes_for :photo, 
:reject_if => proc { |attributes| attributes['image'].blank? || attributes['photo_title'].blank?}, 
:allow_destroy => true 
+0

同樣的事情正在發生,所以我猜這是一個更深層次的問題。我已經設置:_destroy =>「1」在這兩個領域,所以不知道爲什麼它不工作。 – LondonGuy

相關問題