Search code examples
ruby-on-railsruby-on-rails-4booleancreation

Return true/false on creation of object


When saving and updating an object, the return value is of boolean type - true or false.

As the create method returns the object as a value, how can I find out if a creation failed or not?


Solution

  • You could try

    @object = Blah.create()
    @object.persisted? # true or false
    

    also if you want to throw an error instead you could use the bang version, be sure to use rescue

    @object = Blah.create!()