我的模型的 cropping
方法在一个循环中被调用,这个循环在我更新 Controller 中的用户属性后永不结束。
用户 Controller 代码
-
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
用户模型代码
-
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
再次触发导致循环。
有没有办法在更新后只调用一次该方法?
最佳答案
我通过从模型中删除 after_update
并从 Controller 的函数本身进行调用来解决这个问题。
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
谢谢!
关于ruby-on-rails - after_update 回调导致模型中永无止境的循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13763274/