2013-05-01 45 views
7

我真的很喜歡first_or_create方法:First_or_create與比賽更新?

# Find the first user named Scarlett or create a new one with a particular last name. 
User.where(:first_name => 'Scarlett').first_or_create(:last_name => 'Johansson') 
# => <User id: 2, first_name: 'Scarlett', last_name: 'Johansson'> 

我不知道我怎麼也有這樣的更新與姓氏「約翰松」的用戶,如果它不存在或不同。尋找最簡單的方法。類似於上述的一個班輪將是理想的。

一種可能的方法是using first_or_initialize combined with update_attributes。我對這種方法唯一擔心的是,即使在提供的字段中有100%的匹配,它也會運行更新。

回答

6

first_or_initializeupdate_attributes應該沒問題。 Rails足夠聰明,只要有變化(你應該能夠使用控制檯/日誌來確認),update_attributes只會觸及數據庫。

8

Zaid非常接近正確。

User.where(first_name: 'Scarlett').first_or_create.update(last_name: 'Johansson') 

這裏有詳細的區別。 (注:這是爲Rails 3+和Rails 4+)

  1. first_or_createfirst_or_initialize之間的區別是_initialize使用.new方法,並且不保存記錄VS .create和經銷商的保存它。

  2. .update.update_attributes.update_attributes是當你有值的散列你用什麼,通常從表單來提交類似params之間的差異。在另一方面,.update讓您輕鬆地指定如上圖所示(field_column: value, field_column2: value2)每個屬性等

就這樣扎伊德說,但它同時適用於.update.update_attributes,軌道數據庫更新」 ......只打數據庫中是否有變更...「

+0

更新是一個私有方法。在這種情況下調用它會導致「NoMethodError:私有方法'update'被稱爲...」如果你想在一行中完成所有操作,則需要使用update_attributes。 – 2014-09-21 11:42:13

+0

我不知道你是如何編碼的,但你不應該有任何問題。 我目前在這個格式的視圖和控制器使用此: 'Session.where(USER_ID:@user,legal_case_id:@case).first_or_create.update(last_active:現在)' 更新一直是公衆方法。 (http://apidock.com/rails/ActiveRecord/Relation/update)。 即使您使用的是.update_attributes,它也是Rails 3+(http://apidock.com/rails/ActiveRecord/Persistence/update_attributes)後.update的別名。所以它「幾乎」不應該以任何方式。 – 2014-09-21 20:27:18