Browse Source

Dynamically passing question to validator

pull/39/head
Matthew Phelan 3 years ago
parent
commit
4a8da65a4d
  1. 1
      app/controllers/case_logs_controller.rb
  2. 21
      app/models/case_log.rb

1
app/controllers/case_logs_controller.rb

@ -26,6 +26,7 @@ class CaseLogsController < ApplicationController
previous_page = params[:case_log][:previous_page] previous_page = params[:case_log][:previous_page]
questions_for_page = form.questions_for_page(previous_page).keys questions_for_page = form.questions_for_page(previous_page).keys
answers_for_page = page_params(questions_for_page).select { |k, _v| questions_for_page.include?(k) } answers_for_page = page_params(questions_for_page).select { |k, _v| questions_for_page.include?(k) }
@case_log.custom_validator_options = { previous_page: previous_page }
if @case_log.update(answers_for_page) if @case_log.update(answers_for_page)
redirect_path = form.next_page_redirect_path(previous_page) redirect_path = form.next_page_redirect_path(previous_page)
redirect_to(send(redirect_path, @case_log)) redirect_to(send(redirect_path, @case_log))

21
app/models/case_log.rb

@ -1,6 +1,9 @@
class CaseLogValidator < ActiveModel::Validator class CaseLogValidator < ActiveModel::Validator
def validate_tenant_age(record) def validate_tenant_age(record)
if record.tenant_age < 0 if !record.tenant_age?
record.errors.add :base, "Tenant age can't be blank"
elsif record.tenant_age < 0
record.errors.add :base, "Age needs to be above 0" record.errors.add :base, "Age needs to be above 0"
elsif record.tenant_age > 120 elsif record.tenant_age > 120
record.errors.add :base, "Age needs to be below 120" record.errors.add :base, "Age needs to be below 120"
@ -8,13 +11,23 @@ class CaseLogValidator < ActiveModel::Validator
end end
def validate(record) def validate(record)
if record.tenant_age? question_to_validate = options[:previous_page]
validate_tenant_age(record)
if question_to_validate == "tenant_code"
if !record.tenant_code?
record.errors.add :base, "Tenant code can't be blank"
end
elsif question_to_validate == "tenant_age"
validate_tenant_age(record)
end end
end end
end end
class CaseLog < ApplicationRecord class CaseLog < ApplicationRecord
validate :instance_validations
attr_accessor :custom_validator_options
enum status: { "in progress" => 0, "submitted" => 1 } enum status: { "in progress" => 0, "submitted" => 1 }
validates_with CaseLogValidator def instance_validations
validates_with CaseLogValidator, (custom_validator_options || {})
end
end end

Loading…
Cancel
Save