Search code examples
ruby-on-railsvalidationmodelruby-on-rails-5is-empty

In rails 5, how do I only have one validation message if I leave a field empty/blank?


I'm using Rails 5. I have this in my model ...

  belongs_to :crypto_currency

  validates :crypto_currency, presence: true

The issue is when I save my model from a form, two errors come back if I don't set a value for the "Crypto_currency" field ...

Crypto currency must exist
Crypto currency Please select a value for crypto currency.

This is my config/locales/en.yml file. I still have to work out how to remove the "Crypto currency" words from the "Crypto currency Please select a value for crypto currency." error message, but you can clearly see I have only defined one error message in the file

en:
  activerecord:
    errors:
      models:
        user_notification:
          attributes:
            crypto_currency:
              blank: "Please select a value for crypto currency."

How do I only have one error message for my model's field if it is not entered?

Edit: In respone to comments, here's how I display ther ror messages

  <ul>
  <% @user_notification.errors.full_messages.each do |message| %>
    <li><%= message %></li>
  <% end %>
  </ul>

Solution

  • Try to change your model like this:

    belongs_to :crypto_currency, optional: true
    validates :crypto_currency, presence: true
    

    And

    en:  
      activerecord:
        attributes:
          user_notification:
            crypto_currency: ""
        errors:
          models:
            user_notification:
              attributes:
                crypto_currency:
                  blank: "Please select a value for crypto currency."