2

Not sure about the best way to go about this.

Assuming I have the field capacity, which is a Postgres jsonb datatype, I need to validate that values are present for keys. In my form I am initialising capacity to:

{ reception: "", dinner: "" }

I need to make sure (using Rails validations) that an error is thrown if that json comes in without both of those values entered i.e:

{ reception: "1000", dinner: "300" }

What's the best way of doing it? I could do it client side without an issue, but would like a fallback serverside. Capacities will never be nil at the serverside because I have already initialised it as above, so can't just call a normal presence_of validation.

Is something like this acceptable? Or is there a much better way?

def capacities_has_values
  if capacities.present?
    check_capacities(capacities)
  end
end

def check_capacities(capacities)
  capacities.each do |k, v|
    if k[v] != nil
      errors.add(:capacities, "Please add #{k.to_s} capacity") unless k[v].is_integer?
    end
  end
end

Thanks

ETA doing this:

class String
  def is_integer?
    self.to_i.to_s == self
  end
end

1 Answer 1

2

your code looks good but as I review I found some of the conditions are incorrect, Here is the corrected check_capacities method.

I am assuming capacities = { reception: "1000", dinner: "300" }

def check_capacities(capacities)
  capacities.each do |k, v|
    unless v.present?
      errors.add(:capacities, "Please add #{k.to_s} capacity")
    else
      errors.add(:capacities, "Please add #{k.to_s} capacity in numbers") unless v.to_i.is_integer?
    end
  end
end
Sign up to request clarification or add additional context in comments.

1 Comment

ok, also notice that your k[v] != nil is wrong inside hash loop.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.