情景:
Given that a model called Edition has its community feature enabled
I want all Records under that Edition to validate for the community field
When the community feature is disabled, the community field will NOT be validated
基本上,我正在尝试在ActiveRecord级别编写自定义验证函数,该函数将检查父版本是否具有正确的true / false值。
但我不确定处理此问题的最佳方法。我的直觉就是这样,但我会得到社区的反馈意见:
class Record < ActiveRecord::Base
validate edition_has_communities?
private
def edition_has_communities?
if self.edition.communities_enabled
if community.blank?
errors.add(:community, "must be filled out for this Edition")
end
end
end
end
我担心的是,此方法取决于与验证前定义的版本的关联,并且情况可能并非总是如此。这会是应该在前端验证的吗?
思想?
答案 0 :(得分:0)
看起来这对我来说效果很好,如果你担心版权协会是否已定义,为什么不加一张支票?
if self.edition and self.edition.communities_enabled
对我来说,这不是要在前端验证的东西,我认为你把它放在模型中是对的。有没有真正应该在前端验证的东西?