Rails如何验证可选的表单字段?

时间:2016-10-17 19:12:12

标签: ruby-on-rails forms validation

我有一个可选的表单字段:meetup_apikey和一个自定义验证方法api_key_valid?来检查返回的API请求是否成功。但是我只想检查验证,如果meetup_apikey表单字段不为空(用户在表单提交时输入了内容)。如果meetup_apikey表单字段为空,我想忽略验证并允许表单保存。

查看:http://guides.rubyonrails.org/v2.3.11/activerecord_validations_callbacks.html文档和Validation to ensure uniqueness of but ignoring empty values?

这就是我在我的模型中所拥有的:

validates :meetup_apikey, allow_blank: true
validates :api_key_valid?, :if => :meetup_apikey

def api_key_valid?
    url = "https://api.meetup.com/2/events?key=#{meetup_apikey}&sign=true&photo-host=public&group_urlname=#{meetup_urlname}"
    if !HTTParty.get(url).success?
    errors.add(:meetup_apikey, "Meetup API key must be valid")
    end
end

但即使在:meetup_apikey表单字段中未输入任何内容,这仍然会强制检查。我不确定我错过了什么或写错了。

任何建议都会有所帮助。谢谢!

1 个答案:

答案 0 :(得分:2)

以下是仅当api_key_valid?属性为非空白时才应用meetup_apikey验证的方式:

validates :api_key_valid?, unless: ->(x) { x.meetup_apikey.blank? }