0

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.

Rob
  • 1,835
  • 2
  • 25
  • 53

2 Answers2

0

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
Pascal
  • 8,464
  • 1
  • 20
  • 31
  • How about: `slug.try(:slice!, 0, 19)`? It'll handle `nil` values for `slug`. – Sergii K Jun 15 '16 at 06:06
  • If you use ```try``` then better go for the bang version ```try!```. Personally I don't like try that much but it does the same thing as my ```if``` – Pascal Jun 15 '16 at 06:08
  • Agreed. There is another "syntactic" variation: `slug && slug.slice!(0, 19) && ...`. – Sergii K Jun 15 '16 at 06:16
  • Went with the second option but it doesn't slice the slug. Just gives the validation error – Rob Jun 15 '16 at 07:08
0

Validations generally add errors to the model if the data is bad. It seems like that's not what you're going for; you just want to truncate the slug if the model's key_type == 4, right? How about just:

before_validation :truncate_slug

def truncate_slug
  self.slug = slug.try!(:slice, 0, 19) if key_type == 4
end
jmschles
  • 274
  • 1
  • 6