2012-02-06 10 views
0

before_addブロックで例外を発生させるrailsガイドによると、多くの場合、オブジェクトがコレクションに追加されなくなります。しかし、例外の発生はactive_recordによって処理されません。has_manyコレクションにアイテムを追加中に制限する

class Order < ActiveRecord::Base 
    belongs_to :customer 
end 

class Customer < ActiveRecord::Base 
    has_many :orders, :before_add => :check_credit_limit 

    def check_credit_limit(order) 
    #If a before_add callback throws an exception, the object does not get added to the collection. 
    raise 'Value cannot be greater than 450' if order.value > 450 
    end 
end 

Failure/Error: customer.orders << order 
value cannot be greater than 450 

これを正常に処理するにはどうすればよいですか?

+0

あなたは 'order'モデルで検証していませんか? –

+0

はいオーダーモデルではできますが、 のような他のシナリオでは、order.value> 450およびself.type == 'Normal''の場合、' raise '値は450より大きくできません。優雅に例外を処理してください –

+1

私はあなたが何を求めているのか分かりません。例外を発生させる場合は、それを自分で処理し、レスキュー方法を理解する必要があります。 –

答えて

0

ご注文クラスに検証を追加することができます。

class Order < ActiveRecord::Base 
    validate :check_value_limit 

    def check_value_limit 
    errors.add(:value, "can not be greater than 450") if value > 450 
    end 
end 

以上かすさんのコメントのための一例として、あなたのオブジェクトにエラーを追加し、手動で例外を処理する必要があります。これは、作成時の処理の基本的な例です。

オブジェクトにエラーを追加するために、あなたの検証メソッドを更新:

customer.rb

def check_credit_limit(order) 
    #If a before_add callback throws an exception, the object does not get added to the collection. 
    if order.value > 450 
     errors.add(:base, "Value can not be greater than 450") 
     raise 'Value cannot be greater than 450' 
    end 
    end 

あなたのコントローラで作成した上での例外を処理する例:

def create 
    @customer.new(params[:customer]) 
    if @customer.save 
    … 
    else 
    render :action=>"new" 
    end 
rescue 
    render :action=>"new" 
end 

あなたをカスタム例外タイプを追加してそれを救助することができます。これにより、他の例外も引き続き正しくスローされます。

関連する問題