Changing or updating an attribute value during a Rails ActiveRecord check

Synopsis . I am trying to change the value of an attribute in a custom ActiveModel::EachValidatorvalidator. Given the following prototype:

def validate_each(record, attribute, value)

trying to install value = thing, seems to be doing nothing - am I missing something? There must be a smart way to do this ...

More details . I accept the URL as part of the site. I don’t want to just use the URL and directly verify that it is returning a message 200 OK, because it will ignore entries that did not start with http, or left leading www, etc. I have some custom logic to handle these errors and follow call forwarding. Thus, I would like the validation to succeed if the user enters example.org/article, and not http://www.example.org/article. The logic works correctly inside the check, but the problem is that if someone enters in the first, the stored value in the database is in the "wrong" form, and not in a well-updated one. Can I change the record during the test to a more canonical form?

+5
source share
1 answer

You must leave a check to do just that: validate ; this is not the right place to manipulate your model attributes.

See ActiveModel before_validation callback. This is a more suitable place to manipulate model attributes in preparation for validation.

It looks like you should inform your ActiveModel implementation of callbacks, at least in accordance with this SO question .

class YourModel
  extend ActiveModel::Callbacks
  include ActiveModel::Validations
  include ActiveModel::Validations::Callbacks

  before_validation :manipulate_attributes

  def manipulate_attributes
    # Your manipulation here.
  end
end
+11
source

All Articles