【问题标题】:undefined method `find_or_create'未定义的方法`find_or_create'
【发布时间】:2012-05-07 11:09:01
【问题描述】:

我想使用以下命令更新数据库中的记录

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 定义了上述方法。

可能出了什么问题?

【问题讨论】:

  • 你使用的是 rails 4 版本的方法。

标签: activerecord ruby-on-rails-3.2


【解决方案1】:

它的 find_or_create_by 和它在 Rails 3 中已弃用。

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

【讨论】:

  • 我不认为这是完全正确的。 find_or_create_by 未被弃用。不推荐使用的是相关的动态生成方法,例如 find_or_create_by_bar
【解决方案2】:

根据Rails 4 docs 使用:

User.find_or_create_by(first_name: 'Joe')

代替:

User.find_or_create_by_first_name('Joe')

【讨论】:

    【解决方案3】:

    我的 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">
    

    【讨论】:

    • 你需要使用Model.find_or_create_by_field(attributes_hash)。但是你使用了find_or_create是错误的。
    【解决方案4】:

    ~> Rails 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-17
      • 2013-06-11
      • 2010-12-30
      • 2019-12-25
      • 2021-07-25
      相关资源
      最近更新 更多