Pregunta

I'm building a simple JSON API using the rails-api gem.

models/user.rb:

class User < ActiveRecord::Base
  has_secure_password
  attr_accessible :email, :password, :password_confirmation

  validates :email, presence: true, uniqueness: { case_sensitive: false }, format: { with: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i }
  validates :password, presence: { on: :create }, length: { minimum: 6 }
end

When I try to sign up without a password this is the JSON output I get:

{
  "errors": {
      "password_digest": [
          "can't be blank"
      ],
      "password": [
          "can't be blank",
          "is too short (minimum is 6 characters)"
      ]
   }
}

Is it possible to hide the error message for password_digest? I'm returning the @user object with respond_with in the controller.

I've tried the following but no luck (it just duplicates the error "can't be blank"):

validates :password_digest, presence: false
¿Fue útil?

Solución

@freemanoid: I tried your code, and it didn't work. But it gave me some hints. Thanks! This is what worked for me:

models/user.rb

after_validation { self.errors.messages.delete(:password_digest) }

Otros consejos

You can manually delete this message in json handler in User model. Smth like:

class User < ActiveRecord::Base
  def as_json(options = {})
    self.errors.messages.delete('password_digest')
    super(options)
  end
end
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top