开发者

Validating and ActiveRecord model based on an associated Model's data?

开发者 https://www.devze.com 2022-12-28 05:32 出处:网络
SCENARIO: Given that a model called Edition has its community feature enabled I want all Records under that Edition to validate for the community field

SCENARIO:

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

Basically, I am trying to write a custom validation function a开发者_JAVA百科t the ActiveRecord level, that will check if the parent edition has the proper true/false value.

But I am not sure the best way to handle this. My instinct is something like this, but I though I would get the communities' feedback:

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

My concern is, that this method depends on the association with the Edition being defined prior to validation, and that may not always be the case. Would this be something that should be validated on the front end maybe?

Thoughts?


Looks like that would work just fine to me, and if you're worried about whether the edition association is defined yet, why not just add a check?
if self.edition and self.edition.communities_enabled
To me this isn't something to validate on the front end, I think you're right to put this in the model. Are there things that ever really should be validated on the front end?

0

精彩评论

暂无评论...
验证码 换一张
取 消