开发者

Retrieving an ActiveRecord length validation returns nil

开发者 https://www.devze.com 2023-03-30 23:59 出处:网络
I want to retrieve the maxmimum lenght validation of a ActiveRecord field in one of my views. The foll开发者_运维知识库owing works fine in rails console and returns the correct value :

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

The foll开发者_运维知识库owing 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

What am I doing wrong?


The _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

should do what you want.

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
0

精彩评论

暂无评论...
验证码 换一张
取 消