Is it possible that in the error message of validate_uniqueness_of to show the id of the record that already has the field that i'm checking the uniqueness?
@vimsha's solution may work but I found a way neater way that allows to still use validates_uniqueness_of
rather than creating your own validator:
validates_uniqueness_of :identifier, message: lambda{|x, y| "#{MyModel.find_by_identifier(y[:value]).id} is already taken" }
@usha's uniqueness validation code will incorrectly fail when updating an existing record since Model.find_by_name(name)
returns the record being updated.
validate :uniqueness_of_name
def uniqueness_of_name(current_record)
existing_record = Model.find_by_name(name)
unless existing_record.nil? || existing_record.id == current_record.id
errors.add(:name, "Record #{existing_record.id} already has the name #{name}")
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With