如何在rails中使用验证包含

时间:2014-04-10 22:26:45

标签: ruby-on-rails

class Stadium < ActiveRecord::Base
validates :name, :presence => true
validates :city, :presence => true
validates :contructiondate, :presence => true
validates :capacity, :presence => true
validates :image, :presence => true

validates :name, :uniqueness => true
validates :city, :uniqueness => true
validates :capacity, :numericality => { :only_integer => true, :greater_than_or_equal_to => 0 }
validates :image, :format => { :with => /^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/ix, :message => "Uniforme Invalido", :multiline => true }
validates :city, :inclusion => { :in => %w(Belo Horizonte Brasilia Curitiba Fortaleza Manaus Natal Recife Rio de Janeiro Salvador Sao Paulo),  :message => "%{value} no esta permitido" }

validate :mydate_is_date?

def mydate_is_date?
    errors.add(:contructiondate, 'must be a valid date') if !contructiondate.is_a?(Date)

end
end

我有一个包含问题,它与Natal,Manaus,Salvador这样的词完美配合,但是像“圣保罗”这样的词,“里约热内卢”不起作用,我怎么能解决它?

由于

1 个答案:

答案 0 :(得分:2)

尝试使用反斜杠\转义空格。

没有转义:

> %w(Belo Horizonte Brasilia Curitiba Fortaleza Manaus Natal Recife Rio de Janeiro Salvador Sao Paulo)
=> ["Belo",
 "Horizonte",
 "Brasilia",
 "Curitiba",
 "Fortaleza",
 "Manaus",
 "Natal",
 "Recife",
 "Rio",
 "de",
 "Janeiro",
 "Salvador",
 "Sao",
 "Paulo"]

逃脱:

> %w(Belo Horizonte Brasilia Curitiba Fortaleza Manaus Natal Recife Rio\ de\ Janeiro Salvador Sao\ Paulo)                                        
=> ["Belo",
 "Horizonte",
 "Brasilia",
 "Curitiba",
 "Fortaleza",
 "Manaus",
 "Natal",
 "Recife",
 "Rio de Janeiro",
 "Salvador",
 "Sao Paulo"]