0

I would like load the particular record if it fails the validates_uniqueness constraint.

I have id (primary key) and title in my model. If the user enters a title which is already present if want to search for the record with the title and load that record instead of throwing the error.

Is there a way to do it?

lucapette
  • 20,564
  • 6
  • 65
  • 59
Balaji
  • 31
  • 2
  • 4

1 Answers1

0

You can use the before_validation callback to check validity yourself, and when it fails, trigger the behavior you're looking for. So, one way to do it would be to write code in before_validation, and in there you could do a simple .valid? call, or manually run the validation for uniqueness by itself. When validation fails, you can stop the callback chain, and trigger custom behavior.

before_validation is one of the many ActiveRecord callbacks available to you.

Another, more common way to do it would be, in your controller, instead of just saving you can basically wrap the .save call in an if statement, because .save returns false if validation fails. You can use this as a way to redirect to an alternate action, in the situation you describe.

@new_record = ThingImSaving.new(params[:thing_im_saving]
if @new_record.save
  ...validation has passed, continue the normal path
else
  ...validation has failed, do something else.
end
jefflunt
  • 33,527
  • 7
  • 88
  • 126