我试图找出它有可能执行一个方法调用,在验证期间改变进入数据库的某些属性的信息。所需的工作流程是:用户提交一个url,我验证它,如果它匹配正则表达式,则调用embedly。 embedly函数获取标题和image_url的信息。我也想对title和image_url进行验证,但是在我调用embedly方法之前,这些并不存在。是否可以在几次验证中调用一个方法?
有没有一种办法:1。 验证LINK_URL 2.呼叫embedly方法 3.验证所产生的标题和图片网址属性?
任何帮助表示赞赏:
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; [email protected])'
#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
我不这么认为 - 我认为你必须检查URL的格式在embedly方法 – 2014-10-02 09:16:11