Rob Rob - 5 months ago 9
Ruby Question

Trying to .slice data in the model before it is saved to the db but it isn't working

I'm trying to have the slug length be less than 20 if the

key_type
is
4
.

In the model I have

validate :text_slug_length

def text_slug_length
if key_type == 4
slug.slice(0, 19)
end

end


But this doesn't throw any errors but also doesnt work. Not sure why...

The slug isnt used for values that have a
key_type
of
4
. Data with the
key_type
of
4
can be long slabs of text so it causes length errors when its trying to save a really long slug. I could somehow not save a slug of the
key_type
4
but this way will also stop the errors from long slugs being generated and I figured
.slice
would be easier.

Can someone help on why this doesn't work.

Answer

You don't assign the sliced value.

validate :text_slug_length

def text_slug_length
  if key_type == 4
    self.slug = slug.slice(0, 19)
  end
end

You might want to check for non-nil value of slug first.

Now this does not look like a validation (it does not mark attributes as faulty, it corrects them) but modifies the user input. D'd suggest you use before_validation instead (and maybe add a real validation, though this is not necessary because you make sure slug length is not exceeded).

before_validation :slice_slug
validates :slug, length: {maximum: 20}, if: :validate_slug_length?

def slice_slug
  self.slug = slug.slice(0, 19) if slug.present? && validate_slug_length?
end

def validate_slug_length?
  key_type == 4
end
Comments