abhaygarg12493
abhaygarg12493

Reputation: 1605

Transaction rollback Error object in Rails

I want to show error message which we get in a process of transaction. This is my student.rb (model)

def self.createStudent (user , student , father , mother)
    begin
      transaction do
        father.save!
        mother.save!
        user.save!
        student.mother=mother
        student.father=father
        student.user=user
        student.save
      end
    rescue ActiveRecord::RecordInvalid => invalid
      return 
    end
  end

And this method is called from a controller

Student.createStudent(@user,@student,@father,@mother)

Now I want to check again in controller that upon saving is their any error or not . And send back to view

Upvotes: 1

Views: 2965

Answers (1)

Atri
Atri

Reputation: 5831

You can return values from this method, both when it succeeds or when it fails.

def self.createStudent (user , student , father , mother)
  begin
    transaction do
      father.save!
      mother.save!
      user.save!
      student.mother=mother
      student.father=father
      student.user=user
      student.save
    end 
    return "success"
  rescue ActiveRecord::RecordInvalid => invalid
    return invalid.record.errors
  end
end

Now in your controller you can check for the return value and show the message in view based on the return value.

EDIT (based on your comment):

invalid.record.errors will have the error on which the transaction failed.

Check the doc.

Upvotes: 4

Related Questions