2011-07-17 39 views
0

我需要檢查model的字段列表,像這樣:優雅的方式,如果字段列表不爲空

[:first_name, :last_name, :city] 

如果所有這些領域中充滿

醜陋的代碼可以看看像這樣:

# user.rb 
def update_profile_completed 
    helper = true 
    field_list.each {|field| helper = false if self[field].blank?} 
    self.update_attributes(:profile_completed => true) if helper 
end 

我希望這段代碼能很好地說明我的問題。

+1

這段代碼真的在users_controller中嗎?它看起來像我的模型代碼,在這種情況下,它應該只設置before_save回調中的值(而不是update_attributes) – klochner

+0

當然,這是我的錯誤,它在before_save回調。 :) – methyl

回答

5
def update_profile_completed 
    self.update_attributes(:profile_completed => true) unless [:first_name, :last_name, :city].any?{|f| self[:f].blank? } 
end 
+0

幾乎完美的答案,但它應該是'如果不是',對吧?現在,如果其中一個字段爲空,表達式將返回「true」而不是「false」。 – methyl

+1

我已經注意到了,所以編輯我的回答 – fl00r

+0

我喜歡一行,+1 – apneadiving

0

我使用了以前的答案進行自定義驗證,然後發現它在nil上失敗。我切換到

[:first_name, :last_name, :city].any?{|f| !self[f].present? } 

因爲它會在空白或零。注意!因爲你現在問的是這個'不存在'vs'這是空白'嗎?