Item
a が a に属している可能性がある構造を持っていますClaim
。もしそうなら、そのフィールドの別のものも必要とする必要があります。関連するコード スニペットは次のとおりです。
class Claim
has_many :items
accepts_nested_attributes_for :items
validates_associated :items
end
class Item
belongs_to :claim
validates :amount_paid, :presence => {:if => :claim}
end
そして、これはほとんどすべての場合に機能します。既存の ものを編集してフィールドにClaim
空白を入力しようとすると、必要なエラーが発生します。amount_paid
そして、Claim
この検証にヒットしたときに が存在する必要があります。これも機能した以前の反復では、
validates :claim_id, :presence => {:unless => :new_claim?}
...
def new_claim?
claim.new_record? # would have thrown an error if claim was nil
end
しかし、その上に空白のフィールドを持つ新しい を作成すると、検証はパスしますが、パスする必要はありません。Claim
amount_paid
Items
無駄に、私も試しました
validates :amount_paid, :presence => {:if => :claim_exists?}
...
def claim_exists?
!!claim
end
他のアイデアはありますか?