Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change or update an attribute value during Rails ActiveRecord validation

Summary: I'm trying to alter an attribute's value within a custom ActiveModel::EachValidator validator. Given the following prototype:

def validate_each(record, attribute, value)

trying to set value = thing doesn't appear to do anything -- am I missing something? There should be a smart way to do this...

Detail: I accept a URL input as part of a site. I don't want to just take the URL and directly validate that it returns a 200 OK message, because that would ignore entries that didn't start with http, or left out the leading www, etc. I have some custom logic to deal with those errors and follow redirects. Thus, I'd like the validation to succeed if a user types in example.org/article rather than http://www.example.org/article. The logic works properly inside the validation, but the problem is that if somebody types in the former, the stored value in the database is in the "wrong" form rather than the nicely updated one. Can I change the entry during validation to a more canonical form?

like image 502
aardvarkk Avatar asked Jul 30 '12 18:07

aardvarkk


People also ask

What is the difference between validate and validates in rails?

So remember folks, validates is for Rails validators (and custom validator classes ending with Validator if that's what you're into), and validate is for your custom validator methods.

How does validation work in Rails?

Rails validation defines valid states for each of your Active Record model classes. They are used to ensure that only valid details are entered into your database. Rails make it easy to add validations to your model classes and allows you to create your own validation methods as well.

What is ActiveRecord in Ruby on Rails?

What is ActiveRecord? ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code. When you need to make changes to the database, you'll write Ruby code, and then run "migrations" which makes the actual changes to the database.


1 Answers

You should leave the validation to do just that: validate; it's not the right place to manipulate your model's attributes.

See ActiveModel's before_validation callback. This is a more appropriate place to be manipulating model attributes in preparation for validation.

It looks like you have to tell your ActiveModel implementation about callbacks, at least according to 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
like image 110
deefour Avatar answered Oct 17 '22 05:10

deefour