Question: Custom model name in Rails 4 validation

Question

Custom model name in Rails 4 validation

Answers 2
Added at 2016-12-20 15:12
Tags
Question

I have a class that looks something like this:

class OrganicBipedalLifeform < ActiveRecord::Base
  # Has the field 'name'

  validate :presence_of_name

  private

  def presence_of_name
    errors.add(:base, "name can't be blank") unless name.present?
  end
end

And I want the validation error message to use a custom string that excludes (or modifies) the model name, say 'Human/Vulcan name can't be blank'.

If I want this to be the default message for validation errors on this model, is there a better approach than changing the flash details in every view which might display validation errors? Ie by changing something on the model itself?

Apologies if this has been answered elsewhere. I've found a lot of posts about customising the field name, but none about modifying the name of the model itself.

ETA: @TomDunning @Dan, I think I misidentified the source of the problem (or at least didn't make it sufficiently specific), so am creating a new thread to ask what I hope is a better question.

Answers to

Custom model name in Rails 4 validation

nr: #1 dodano: 2016-12-20 18:12

I think you can replace :base with self.class_name or self.class.table_name or a similar class method.

nr: #2 dodano: 2016-12-20 18:12

That is bad design, just use this:

validate :name, presence: true

"name can't be blank" would be the default error anyway.

If you then want to extract these later just call my_record.errors or similar.

For a custom error message

validate :name, presence: { message: 'must not be blank' }

Source Show
◀ Wstecz