如果有人能帮我的话,我对这个模型有很多问题。目前,无论何时启动update_attributes,我的代码似乎都会导致无限循环。我尝试了许多不同的组合来停止这种情况,但似乎都不起作用(除了非常低效的方法:( )
根据ActiveModel::Dirty,link_url_changed方法应该只在用户编辑链接时返回true,但由于某些原因,它总是返回true,并允许无限循环。怎样才能让它工作呢?
我真的很想1.在一个新的记录中,用户提交一个链接,它是有效的2.如果有效,一个回调调用来获得更多关于链接的信息。3.验证新信息,然后将其存储到数据库中。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非常感谢你的帮助!
发布于 2014-10-04 15:37:47
请不要在回调方法中使用update_attributes,它会触发新的保存。只需像这样更新模型:
self.title = obj[0].title
self.image_url = obj[0]["images"][0]["url"]https://stackoverflow.com/questions/26190679
复制相似问题