In my Rails 4, I have a Post
model I need to implement a custom validation on.
Following the recommendation in this question and in the documentation here, I have implemented the following code:
#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: The facebook_copy_link
method is defined as follows:
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
—————
When I run the app, I get the following error:
NameError at /posts/74/edit
uninitialized constant Post::LinkValidator
validates_with LinkValidator
Any idea what is wrong here?
—————
UPDATE 2: I had forgotten to restart the server.
Now, I get a new error:
NoMethodError at /posts/74
undefined method `facebook_copy_link' for #<LinkValidator:0x007fdbc717ba60 @options={}>
unless facebook_copy_link(record.copy)
Is there a way to include this method in the validator?