2017-06-12 12 views
0

に検証エラーをトリガー:ペーパークリップは、私は私のペーパークリップのモデルでは、この機能を持って破壊する

def ratiocorrect 
    ratio = Paperclip::Geometry.from_file(image.queued_for_write[:original].path).width/Paperclip::Geometry.from_file(image.queued_for_write[:original].path).height 
    if ratio < 1.499 or ratio > 1.501 
     errors.add(:image,'ratio should be 4:3') 
    end 
    end 

画像は3の比率がある場合には、チェックします。それを保存する前に2。

私はこれを強制:

validate :ratiocorrect 

そして、それは完璧に動作します。

けれども、私は、私は次のエラーを取得する画像破壊したい:

undefined method `path' for nil:NilClass 
ratio = Paperclip::Geometry.from_file(image.queued_for_write[:original].path).width/Paperclip::Geometry.from_file(image.queued_for_write[:original].path).height 

アクションを破壊するために何も存在しないとして、それは、再びqueued_for_write画像に対してチェックしているようですが。

作成または更新され、破壊されていない場合のみ検証できますか?

答えて

1

はい、:createおよび/または:updateオプションをカスタム検証で使用します。

あなたはこのようなものでしょう:

validate :ratiocorrect, on: :create 

By default, such validations will run every time you call valid? or save the object. But it is also possible to control when to run these custom validations by giving an :on option to the validate method, with either: :create or :update.

追加情報についてCustom Methodsをチェックアウトします。

+1

パーフェクト。ありがとうございました – Maxence

関連する問題