Ralph King
Ralph King

Reputation: 1064

Rails custom validation for Postgres Json fields

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

Upvotes: 2

Views: 2421

Answers (1)

power
power

Reputation: 1265

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

Upvotes: 2

Related Questions