在分配属性时处理异常并在一对多关系上添加错误

时间:2015-08-21 15:56:19

标签: ruby ruby-on-rails-4 exception-handling rails-activerecord carrierwave

我们有一个订单可以有多张卡的模型。每张卡都与图片相关联。上传图片时有时会发生异常。上传时已加载carrierwave。如何以及在何处捕获此异常并将错误添加到相应的卡(最好是在card.rb类中)?

我想我可以将问题概括为:如何在一对多关系上分配属性并将错误添加到相应字段时如何处理异常?

订单类看起来像这样(简化):

class Order < ActiveRecord::Base

  has_many :cards, class_name: 'Card'
  accepts_nested_attributes_for :cards, allow_destroy: true

end

卡片类看起来像这样(简化):

class Card < ActiveRecord::Base

  mount_uploader :picture, PictureUploader
  crop_uploaded  :picture

end

控制器代码:

class OrderController < ApplicationController

  def submit
      order.assign_attributes(order_params)

      if order.valid?
        ...
      else
        render :show
      end
  end   

  protected

  def order_params
    params.require(:order).permit(
      card_attributes: [:picture_crop_x, :picture_crop_y, :picture_crop_w, :picture_crop_h, :picture, :_destroy]
  end

end

1 个答案:

答案 0 :(得分:0)

我们解决了以下问题:

1)在卡片模型中添加了一个属性:

attr_accessor :crop_failed

2)添加了验证方法:

validate  :crop_success?

def crop_success?
  errors.add(:picture, 'Image cannot be processed.') if crop_failed == true
end

3)在Uploader类中,我们捕获了异常并将属性:crop_failed设置为true。

def crop
  model.crop_failed = nil
  ...
rescue Exception => e
  model.crop_failed = true
end