开发者

validate length of string against another property

I have a model with 2 properties

  • name
  • url_name

I would like to make sure that the number of characters in url_nam开发者_运维百科e is less than or equal to the number of characters in name. I have tried doing something like the following but it doesn't seem to work. Does anyone have any suggestions?

class Country < ActiveRecord::Base
  has_many :product

  validates_presence_of :name, :url_name
  validates_length_of :url_name, :maximum => :name.length

end

I'm new to ruby and rails so forgive me for my lack of understanding of some of the basic concepts in the language :)


The default validation methods can't do that (they are quite basic), but you can create a custom validation method, for example:

validate :url_length

def url_length
  errors.add(:url_name, "error") unless url_name.length <= name.length
end
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜