简体   繁体   中英

Trigger rails/active_record conditional validation without conditionals

I have a model that has three specific states: draft , submitted and published .

Each of these states has specific validation rules. Eg the name of the model is only required in submitted and published . Something along the lines of:

validates :name, :presence => true, :unless => :draft?

When a draft model is on-screen, I want to show which broken validation rules have to be fixed, before being able to transition to submitted . When the model is in draft , the validation states that it is valid (which is true), but I still want to show the errors as if it were submitted .

I'm don't really know how I should tackle this problem.

I do something similar for one of my projects. In my case, I have a virtual attribute that I can set to override the state. Then in my version of the "draft?" method I check the virtual attribute, if the attribute "do_full_validation" is set to true, then I respond in a way that allows the validation to be executed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM