title: Validation Error Messages for belongs_to Assocations made easy
body: <p>I have quite some belongs_to associations in my application, some of them are optional (i.e. the association could be nil), some are mandatory (association must be a valid parent record.</p>
  
  <p>My initial approach was to validate the given id using my own validation method (here for a mandatory association)</p>
  
  <pre><code>belongs_to :category
  
  validates :category_id, 
    presence: true
  
  validate given_category_exists
  
  def given_category_exists
    if category_id.present?
      errors.add( :category_id, 'must be present' ) \
        Category.exists?( category_id )
    end
  end
  </code></pre>
  
  <p>Then I found out that Rails would do this for me if I would use the presence check on the association so I could omit my own validation method:</p>
  
  <pre><code>belongs_to :category
  
  validates :category,
    presence: true
  </code></pre>
  
  <p>But now, the generated error message would simply state: <code>Category can't be blank</code>. The problems here are: (1) Can I provide a more useful message? (2) How can I insert my own translation for the attribute? <code>Category</code> is the default label generated from the validates method, <code>can't be blank</code> is the default error text for :blank.</p>
  
  <p>Another problem with this: The related input field in the form is not marked as 'field_with_errors' as this field is identified with the attribute's name, not the association's name.</p>
  
  <p>Using the standard way of doing things, I would add an additional attribute to my I18n translation file for the name of the association <code>category</code> and adding a replacement for the standard message:</p>
  
  <pre><code>en:
    activerecord:
      models:
        attributes:
          my_model:
            category_id: 'This Category'
            category:    'This Category'
  
      errors:
        models:
          my_model:
            attributes:
              category:
                blank:  'must be specified.'
  </code></pre>
  
  <p>Lots of lines where things can go wrong. And I did not like the idea to add superficial attributes which are actually not attributes but names of associations.</p>
  
  <p>Is there an easier way?</p>