stephskardal / rails_admin_import

Rails Admin Import functionality
http://www.endpoint.com/
MIT License
160 stars 122 forks source link

How to add custom errors when import fails #137

Open davideluque opened 1 year ago

davideluque commented 1 year ago

I want to show custom errors when the association is not present or unique.

Rails uniqueness validation adds these errors: MyAssociation has been taken / MyAssociation must exist

When I try

validates :my_association, uniqueness: {message: "This is my custom message"}

It shows

My Association has been taken. My Association This is my custom message

I am also trying to add other errors not related to validations but to finding a model related to this.

My code:

class Report < ApplicationRecord
  validates :my_association, uniqueness: true

  def after_import_error(record)
    if CustomModel.find(record[:custom_attribute])
      self.errors.add(:base, "Custom attribute does not exist")  # This does not work! The error is not added
  end
end

Probably a Rails-related question but I would love it if you could help in combination with Rails Admin.

Thanks!

davideluque commented 1 year ago

It would be nice to modify the entire error string, is that possible?

davideluque commented 1 year ago

I also tried to add the error in the before_import_save

  def before_import_save(record)
    custom_model = CustomModel.find(record[:custom_attribute])

   errors.add(:base, "Custom message") unless custom_model
  end
monkbroc commented 1 year ago

Hi. I don't have a ready made answer for you here. If you are willing to dig into the code of the gem and the rails admin gem to find out where error messages are constructed, and how to add a hook for a custom error message, please open a PR. Make sure to add a paragraph in the README on how to set up custom error messages.