如果有人可以提供帮助,我会对这个模型遇到很多麻烦。目前,我的代码似乎在启动update_attributes时导致无限循环。我已经尝试了很多不同的组合来阻止它,但似乎没有任何效果(除非效率很低的方法:()
根据ActiveModel :: Dirty,link_url_changed方法只应在用户编辑链接时返回true,但由于某种原因,它始终返回true并允许无限循环。怎么让这个工作?
我真的很喜欢1.在新记录中,用户提交一个链接,它被验证2.如果有效,则回调调用嵌入以获取链接上的更多信息。 3.验证新信息,然后存储到db 4中。不再调用embedly!直到用户编辑link_url
这是我的代码:
class ListLink < ActiveRecord::Base
include ActiveModel::Dirty
belongs_to :list
default_scope -> {order('created_at DESC')}
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}
validates :list_id, presence: true
before_save :embedly, if: "link_url_changed?"
#need to trigger embedly only when link_url changes
validates :title, presence: true#, length:{minimum: 4, maximum: 200}
validates :image_url, presence: true
private
def embedly
logger.debug "embedly entered link changed!"
#if self.errors.empty?
embedly_api = Embedly::API.new :key => 'xxxxxxxxxxxxxxxxxxxxxxxxx',
: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
update_attributes(:title => obj[0].title, :image_url => obj[0]["images"][0]["url"])
end
end
非常感谢您的帮助!
答案 0 :(得分:0)
不要在回调方法中使用update_attributes
,它会触发新的保存。只需像这样更新模型:
self.title = obj[0].title
self.image_url = obj[0]["images"][0]["url"]