2014-12-26 74 views
3

所以我有一個Profile對象的多態子元素。如果特定對象的字段爲空,模型被設計爲銷燬after_save。Rails:只對CREATE動作使用REJECT_IF嵌套屬性

但是,對於accept_nested_attributes,如果它是空白的,我不想首先創建子對象。但是,如果我離開reject_if語句,則用戶不再有能力在UPDATE上清空字段,因爲reject_if會拒絕其空白輸入。我想要reject_if: { ... }, on: :create。但這似乎並不奏效。

+0

':create'是與'validates'組合使用。 'accept_nested_attributes_for'沒有這個選項。請參閱http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html#method-i-accepts_nested_attributes_for –

回答

7

您可以創建一個方法,而不是發送一個進程進入reject_if選項,這是一樣的,它只是更具可讀性,所以代碼看起來像:

accepts_nested_attributes_for :socials, reject_if: :social_rejectable? 

private 

def social_rejectable?(att) 
    att['username'].blank? && new_record? 
end 

您可以重複剛纔的方法,然後用一些元編程它清理乾淨或添加new_record?方法對proc

accepts_nested_attributes_for :socials, reject_if: proc { |att| att['username'].blank? && new_record?} 
+1

未定義的方法'new_record?'爲#

+0

嘗試沒有proc,而是使用完整的方法在這種情況下'social_rejectable?(att)'它爲我工作 – kurenn

+0

是的完整的方法似乎工作。謝謝。 –