首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在模型中导致永不结束循环的after_update回调

在模型中导致永不结束循环的after_update回调
EN

Stack Overflow用户
提问于 2012-12-07 20:39:19
回答 2查看 1.6K关注 0票数 2

我的模型的cropping方法是在一个循环中调用的,这个循环在我更新控制器中的用户属性之后永远不会结束。

User controller code-

代码语言:javascript
复制
   def change_img  
      @user = current_user

      #this triggers the model's after_update callback
      @user.update_attributes(params[:user])  

      flash[:notice] = "Successfully updated Image."  
      render :action => 'crop'  
   end  

User Model code-

代码语言:javascript
复制
after_update :reprocess_avatar, :if => :cropping? 


  def cropping?  
   #this method is called infinitely why?

  !crop_x.blank? && !crop_y.blank? && !crop_w.blank? && !crop_h.blank? 

  end  

一旦设置了crop_x、crop_y、crop_w和crop_h,cropping方法将始终返回true,它将继续调用reprocess_avatar方法。这可能是因为reprocess_avatar方法也在更新用户表的avatar属性。因此,after_update再次触发,导致循环。

有没有办法在更新后只调用一次方法?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-12-07 21:45:20

我通过从模型中删除after_update并从控制器的函数本身进行调用来解决了这个问题。

代码语言:javascript
复制
   def change_img  
      @user = current_user         
      @user.update_attributes(params[:user]) 

      if(!@user.crop_x.blank? && !@user.crop_y.blank? && 
     !@user.crop_w.blank? &&  !@user.crop_h.blank?)
         @user.avatar.reprocess! 
      end

      flash[:notice] = "Successfully updated Image."  
      render :action => 'crop'  
   end  

谢谢!

票数 7
EN

Stack Overflow用户

发布于 2012-12-07 20:57:30

如果reprocess_avatar正在更新某些内容,请确保您正在使用任何非回调更新方法,这样就不会在对象中触发任何进一步的回调。例如,如果您要在DB表示上设置标志或更新某些id列或设置时间戳,请使用一些直接到数据库的方法,如#update_column或#touch。但是,如果看不到reprocess_avatar方法的实际内容,就很难给出更好的建议。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13763274

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档