问题
History: How to display a presence validation conditionally in combination with carrierwave?
I'm building an object with this gem: https://github.com/schneems/wicked/wiki/Building-Partial-Objects-Step-by-Step
validates :name, :presence => true, :if => :active_or_name?
validates :details, :presence => true, :if => :active_or_details?
validates :image, presence: true, image_size: { width: { min: 400 },
height: { min: 400 } }, :file_size => { :maximum => 5.megabytes.to_i },
if: :active_or_details?
with the functions:
def active?
status == 'active'
end
def active_or_name?
status.include?('name') || active?
end
def active_or_details?
status.include?('details') || active?
end
how I set the status is:
params[:item][:status] = step.to_s
params[:item][:status] = 'active' if step == steps.last
The last step is 2 steps after the details page, so it should not be 'active'.
In the History (link above) you can read that I should be adding the following to the if:
of the image validation:
-> (record) { record.image_integrity_error.blank? }
I tried to add the above line with
validates :image, presence: true, image_size: { width: { min: 400 },
height: { min: 400 } }, :file_size => { :maximum => 5.megabytes.to_i },
if: :active_or_details? && -> (record) { record.image_integrity_error.blank? }
This causes the validation on the page to show only the
Image You are not allowed to upload "txt" files, allowed types: jpg, jpeg, gif, png
But now the validation happens on each page of the before needed submission steps with Image can't be blank
.
I tried to refactor the -> (record) { record.image_integrity_error.blank? }
into the active_or_details?
with an if/else statement. Then the Image can't be blank
returns on the details page .
Please advise.
回答1:
As per comment @engineersmnky: if
keyed conditions can be submitted as an Array
e.g. if: [:active_or_details?,-> (record) { record.image_integrity_error.blank? }]
来源:https://stackoverflow.com/questions/48120545/how-to-correctly-add-the-record-image-integrity-error-to-existing-condition