我有一个结构,其中 anItem
可能属于 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
还有其他想法吗?