我試圖找出它有可能執行一個方法調用,在驗證期間改變進入數據庫的某些屬性的信息。所需的工作流程是:用戶提交一個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