Recuperar una validación de longitud de ActiveRecord devuelve nil

I want to retrieve the maxmimum lenght validation of a ActiveRecord field in one of my views.

The following works fine in rails console and returns the correct value :

irb(main):046:0> micropost = Micropost.new
=> #<Micropost id: nil, content: nil, user_id: nil, created_at: nil, updated_at: nil>
irb(main):047:0> micropost._validators[:content][1].options[:maximum].to_s
=> "140"

However, when I use the same code in my controller it returns nil :

class PagesController < ApplicationController

  def home
    @title = "Home"
    if signed_in?      
      @micropost = Micropost.new
      @feed_items = current_user.feed.paginate(:page => params[:page])
      @content_max = @micropost._validators[:content][1].options[:maximum].to_s
    end
  end

...

end

I also tried to include a method in my ApplicationHelper, which also returns nil ;-(

def content_max
  Micropost._validators[:content][1].options[:maximum].to_s
end

¿Qué estoy haciendo mal?

preguntado el 27 de agosto de 11 a las 16:08

Has my solution worked for you? -

1 Respuestas

Al _validators array might not be in the same order whether you're in the console or in a web request.

Micropost._validators[:content].find {|v| v.class == ActiveModel::Validations::LengthValidator} .options[:maximum].to_s

debe hacer lo que quiera.

IMHO, a better solution would be to store the length in a constant (I somehow doubt the _validators array is part of the official API) :

class Micropost < ActiveRecord::Base
    MAX_CONTENT_LENGTH = 140

    validates :content, :length => {:maximum => MAX_CONTENT_LENGTH}

    # Rest of the code...
end

and get the length with :

Micropost::MAX_CONTENT_LENGTH

Respondido 27 ago 11, 20:08

Hi Benoit, I tried your first solution and it worked fine, except when submitting the page with too many characters in the input field, the @variable I assigned the _validators value to, turned out to be nil for some reason. Maybe this variable is outside the scope of the shared/_error_messages partial? Anyway, because of this and your concern about the _validators array being part of the official API, I decided to implement your second solution (which I also find much cleaner) and added a helper method to get the length in my views. Thanks for helping me out. - Peter

You're welcome. Ruby is awesome because it lets you muck with the internals of the libraries you're using, but it sometimes can hurt you (not that I haven't been guilty of doing it ;-) ). - Benoit Garret

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.