6

次のコマンドを使用して、データベースのレコードをアップサートしたい

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"  )

はどこProfileですかactiverecord model

しかし、次のエラーが発生します

undefined method find_or_create for Profile class

Profile.public_methodsfind_or_createメソッドは示していませんがActiverecord Api、上記のメソッドを定義しています。

何が間違っている可能性がありますか?

4

4 に答える 4

11

それとfind_or_create_by、Rails 3 では非推奨です。

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

于 2012-05-07T11:32:59.273 に答える
4

用途に応じてRails 4 docs

User.find_or_create_by(first_name: 'Joe')

それ以外の:

User.find_or_create_by_first_name('Joe')
于 2016-11-24T13:05:34.500 に答える
1

私のRailsバージョン

Rails -v
  Rails 3.1.3

私のRubyバージョン

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">
于 2012-05-07T11:56:41.780 に答える
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
于 2015-08-15T21:59:19.913 に答える