【发布时间】:2016-03-24 08:50:34
【问题描述】:
在我的 Rails 4 中,我有一个 Post 模型,我需要在其上实现自定义验证。
按照in this question和in the documentation here的建议,我实现了以下代码:
#app/validators/link_validator.rb
class LinkValidator < ActiveModel::Validator
def validate(record)
if record.format == "Link"
unless facebook_copy_link(record.copy)
record.errors[:copy] << 'Please make sure the copy of this post includes a link.'
end
end
end
end
#post.rb
class Post < ActiveRecord::Base
[...]
include ActiveModel::Validations
validates_with LinkValidator
[...]
end
————
UPDATE:facebook_copy_link方法定义如下:
class ApplicationController < ActionController::Base
[...]
def facebook_copy_link(string)
require "uri"
array = URI.extract(string.to_s)
array.select { |item| item.include? ( "http" || "www") }.first
end
[...]
end
————
当我运行应用程序时,我收到以下错误:
NameError at /posts/74/edit
uninitialized constant Post::LinkValidator
validates_with LinkValidator
知道这里有什么问题吗?
————
更新 2:我忘记重新启动服务器。
现在,我收到一个新错误:
NoMethodError at /posts/74
undefined method `facebook_copy_link' for #<LinkValidator:0x007fdbc717ba60 @options={}>
unless facebook_copy_link(record.copy)
有没有办法将此方法包含在验证器中?
【问题讨论】:
标签: ruby-on-rails validation ruby-on-rails-4 activemodel