2012-05-07 43 views
6

我想用給UPSERT在數據庫記錄下面的命令未定義的方法`find_or_create」

Profile.find_or_create(fname: contact.FirstName, lname: contact.LastName, 
    company: account.Name, title: contact.Title, user_id: contact.CreatedById, 
    account_id: account.Id, contact_id: contact.Id, type: "contact" ) 

其中Profileactiverecord model

undefined method find_or_create for Profile class 

Profile.public_methods沒有我得到以下錯誤顯示find_or_create方法,但Activerecord Api定義了上述方法。

什麼可能是錯誤的?

+0

您使用的是軌道4版的方法。 – RGB

回答

10

find_or_create_by及其在Rails的3棄用

使用@foo = Foo.find_by_bar("baz") || Foo.create(:bar => "baz")

+3

我不認爲這是真的。 'find_or_create_by'不被棄用。這是相關的動態生成的方法,如'find_or_create_by_bar',這是不贊成的。 – barendt

1

我的Rails版本

Rails -v 
    Rails 3.1.3 

我的紅寶石版本

Ruby -v 
    ruby 1.9.2p290 

在Rails控制檯我能使用

find_or_create_by method like below 

1.9.2-p290 :001 > User.find_or_create_by_name("soundar") 
User Load (0.8ms) SELECT `users`.* FROM `users` WHERE `users`.`name` = 'soundar' LIMIT 1 
=> #<User id: 1, name: "soundar", age: 23, created_at: "2012-04-17 11:12:43", updated_at: "2012-04-17 11:12:43"> 
+0

mine是'Rails -v 3.2.3' –

+1

您需要使用Model.find_or_create_by_field(attributes_hash)。但是您已經使用了find_or_create這是錯誤的。 –

0

〜>軌道4

["Goose Island IPA", "Dogfish Head 90 Min IPA", "Mother Earth Oatmeal Stout", "Raleigh Brewing Mocha Stout"].each do |beer| 
    Beer.find_or_initialize_by(name: beer) 
end 
2

由於每Rails 4 docs使用:的

User.find_or_create_by(first_name: 'Joe') 

代替:

User.find_or_create_by_first_name('Joe')