Ruby on Rails Active Record return value when create fails?

后端 未结 2 870
情书的邮戳
情书的邮戳 2021-02-13 00:02

I am new to ruby on rails and having trouble getting this work. Basically I have a user registration page which has a password confirmation. In the User class I have the followi

2条回答
  •  情书的邮戳
    2021-02-13 00:28

    The answer is the ActiveRecord object. The official source code shows that create return the object if it succeeds or fails:

    # File activerecord/lib/active_record/persistence.rb, line 29
    def create(attributes = nil, &block)
      if attributes.is_a?(Array)
        attributes.collect { |attr| create(attr, &block) }
      else
        object = new(attributes, &block)
        object.save
        object
      end
    end
    

    How to judge it succeeds or fails

    The real answer is persisted?:

    if user.persisted?
      # Success
    else
      # Failed
    end
    

    Why didn't use user.valid? to do it? Because sometimes it is not enough when there are some callbacks which operate other models failed:

    class One < ActiveRecord::Base
      has_many :twos
      after_create :create_twos_after_create
      def create_twos_after_create
        # Use bang method in callbacks, than it will rollback while create  two failed 
        twos.create!({})    # This will fail because lack of the column `number`
      end
    end
    
    class Two < ActiveRecord::Base
      validates :number, presence: true
    end
    

    Now, we execute One.create will fail, check the log file, it will be a rollback because it failed to create two. In this case, One.create.valid? still return true, but it actually created failed, so use One.create.persisted? to replace it is necessary.

    Notice: The code is tested in Rails 5.1.

提交回复
热议问题