Passing extra data to find_or_create

后端 未结 2 609
旧时难觅i
旧时难觅i 2020-12-29 08:15

Something I\'ve always wondered about rails is the ability to pass extra data to find_or_create methods in rails. For example, I can\'t do the following

User         


        
相关标签:
2条回答
  • 2020-12-29 09:00

    With rails 4.x

    DEPRECATION WARNING: This dynamic method is deprecated. Please use e.g. Post.find_or_create_by(name: 'foo') instead
    

    Use this

    User.find_or_create_by(first_name: 'Scarlett') do |user|
      user.last_name = 'Johansson'
    end
    
    0 讨论(0)
  • 2020-12-29 09:12

    Try this:

    User.find_or_create_by_name(:name=>'ceilingfish', 
            :email => 'an_email@a.domain', :legs => true, :face => false)
    

    When you have additional parameters to find_or_create_by_, you have to pass all the parameters as a hash.

    Rails 4

      User.create_with(
        email: 'an_email@a.domain', 
        legs: true, face:false
      ).find_or_create_by(:name=>'ceilingfish')
    
    0 讨论(0)
提交回复
热议问题