1

I would like to validate attributes in a function like this

class User < ActiveRecord::Base

  validate :check_name( :name )

  def check_name( name )
    ... if name is invalid ...
       self.errors.add( :name, 'Name is invalid')
  end

end

Can you please write the right code? Please explain the functionality why... THX!

1 Answer 1

6
class User < ActiveRecord::Base

  validate :check_name

  def check_name
    if name # is invalid ...
      self.errors.add(:name, 'Name is invalid')
    end
  end

end

You can use the validate macro but the method can't accept parameters. You need to fetch the attribute value from inside the method, then validate it.

Replace

if name # is invalid ...

with your own validation logic.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.