Pavel Tarno
Pavel Tarno

Reputation: 1324

validates_length_of with a variable

I have an ActiveRecord model:

class Message < ActiveRecord::Base

which has 2 attributes: content(string) and max_content_length(integer) both are dynamic and set by the user.
I'm trying to validate the length of the content string using the max_content_length integer like so:

validates_length_of :content, maximum: self.max_content_length

or like so:

validates_length_of :content, maximum: lambda{ self.max_content_length }

but validates_length_of throws either a "no method found" or a "maximum must be a nonnegative Integer or Infinity" exception (respectively).

Is there any other way to "register" the max_content_length function as the validator for the length?

Thank you!

(I know this is question is possibly a duplicate for this question and this one but unfortunately the answers there are a little off-topic and confusing)

Upvotes: 2

Views: 927

Answers (1)

James Daniels
James Daniels

Reputation: 6981

Make your own validation:

class Message < ActiveRecord::Base

  validate :validate_content_length

  private

  def validate_content_length
    if content.length > max_content_length
      errors.add :content, "too long (must be #{max_content_length} characters or less)"
    end
  end

end

Help guides here http://guides.rubyonrails.org/active_record_validations.html#performing-custom-validations

Upvotes: 2

Related Questions