我试图找出在验证过程中执行一个方法调用的可能性,该方法调用可以更改数据库中的某些属性的信息。所需的工作流是:用户提交一个url,我验证它,如果它与regex匹配,则调用嵌入式。嵌入式函数获取标题和image_url的信息。我也想在标题和image_url上执行验证,但是直到我调用了嵌入式方法之后,它们才会存在。
是否有一种方法: 1.验证link_url 2.调用嵌入式方法3.验证结果标题和image_url属性?
如有任何帮助,我们将不胜感激:
class ListLink < ActiveRecord::Base
belongs_to :list
default_scope -> {order('created_at DESC')}
#the REGEX urls are matched against
VALID_URL_REGEX = /\A(http:\/\/|https:\/\/|www|)[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?\/.*)?\z/i
validates :link_url, presence: true,
format:{with: VALID_URL_REGEX, message: "Please enter a valid url."}
validates :list_id, presence: true
#if is a valid url, ping embedly for more information on it
before_save :embedly
#is it possible to call just these 2 validations after the :embedly method?
validates :title, presence: true, length:{minimum: 4, maximum: 200}
validates :image_url, presence: true
private
def embedly
embedly_api = Embedly::API.new :key => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
:user_agent => 'Mozilla/5.0 (compatible; mytestapp/1.0; my@email.com)'
#duplicate the url for use in the embedly API
url = link_url.dup
obj = embedly_api.extract :url => url
#extract and save a title and image element to the database
self.title = obj[0].title
self.image_url = obj[0]["images"][0]["url"]
end
end发布于 2014-10-02 09:24:28
您可以编写一个before_validation回调,它检查您的link_url以及它是否有效(如果它与URL匹配),执行您的嵌入式内容。然后,在常规验证期间,仍然可以将错误消息添加到无效的link_url中。这可能是这样的:
class ListLink < ActiveRecord::Base
before_validation :embedly_if_valid
# the REGEX urls are matched against
VALID_URL_REGEX = /\A(http:\/\/|https:\/\/|www|)[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?\/.*)?\z/i
validates :link_url, presence: true,
format:{with: VALID_URL_REGEX, message: "Please enter a valid url."}
validates :list_id, presence: true
validates :title, presence: true, length:{minimum: 4, maximum: 200}
validates :image_url, presence: true
private
def embedly_if_valid
embedly if self.link_url =~ VALID_URL_REGEX
end
def embedly
embedly_api = Embedly::API.new :key => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
:user_agent => 'Mozilla/5.0 (compatible; mytestapp/1.0; my@email.com)'
#duplicate the url for use in the embedly API
url = link_url.dup
obj = embedly_api.extract :url => url
#extract and save a title and image element to the database
self.title = obj[0].title
self.image_url = obj[0]["images"][0]["url"]
end
end请注意,如果title和image_url字段无效,则可能会收到验证错误。如果不希望通过在link_url钩子中将nil设置为nil,则可能会对其进行编码,除非它是有效的。
发布于 2014-10-02 09:28:21
与其使用before_save回调,我建议在link_url的自定义设置器中这样做,类似于.
def link_url=(url)
if url =~ VALID_URL_REGEX
super
embedly
end
end或者,如果您没有调用link_url = ...,请在before_validation回调中这样做。
发布于 2014-10-02 09:28:58
你不能按你说的那样做。根据对象的状态,您似乎有不同的验证。
相反,您可以在保存之前运行embedly,然后验证所有内容。如果需要进行一些验证才能使用embedly方法,则可以使用表单对象(示例3)来分隔流程的不同步骤。
您也可以使用before_validation来运行embedly,但是它使您需要在embedly所需的字段上复制验证(在验证之前,您需要在您的方法中测试它,然后对模型进行测试,以防以后需要重新运行该方法)。您可以通过一个名为“解释”的自定义验证方法来传递它,但我不太喜欢这个方法。
https://stackoverflow.com/questions/26157350
复制相似问题