2014-10-04 65 views
0

如果有人可以帮忙,我对这个模型有很多麻烦。目前,我的代码似乎无论何时启动update_attributes都会导致无限循环。我已经尝试了很多不同的组合来让这个停下来,但似乎没有任何工作(除非效率很低的方法:():尽管有条件,Rails回调会触发吗?

根据ActiveModel :: Dirty,link_url_changed方法应该只在用户有编辑链接,但由于某种原因,它始终返回true,并允许无限循环。如何让这个工作?

我真的很想1.在一个新记录中,用户提交一个链接,它是验证2.如果有效,回调调用嵌入获得更多信息的链接3.新的信息进行验证,然后存储到数据库4.嵌入不会再次调用!直到用户编辑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; [email protected])' 
      #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

在回调方法中不要使用update_attributes,它会触发一个新的保存。只是像这样更新模型:

self.title = obj[0].title 
self.image_url = obj[0]["images"][0]["url"] 
+0

啊是的,我以前这样做,但是这不会跳过验证?你有没有关于如何用这种方法验证数据的建议? – PaygeVii 2014-10-04 07:44:03

+0

@PaygeVii你可以使用'before_validation'而不是'before_save',所以新的标题和image_url将被验证。 – Baldrick 2014-10-04 07:52:41

+0

是的,我之前尝试过before_validation,但后来我无法使asynchornization工作。无论如何,感谢您的帮助! – PaygeVii 2014-10-04 07:53:50