title: Validation of virtual attributes in Ruby on Rails
body: <p>I am running Ruby (1.9.3) on Rails (3.2.0) and having a problem with the validation of virtual attributes.</p>
  
  <p>I have a <code>Flight</code> model that represents a flight which, among others, has an attributes that represents the airport of departure and arrival.</p>
  
  <p>Because the <code>select</code> for selecting an airport is potentially huge, I opted to go for an autocomplete solution, which is working perfectly fine. I am using a <code>before_validation</code> callback to properly populate the actual ID of the airport:</p>
  
  <pre><code>before_validation do
    self.departure_airport = Airport.find_by_long_name(departure_airport_name)
    self.arrival_airport = Airport.find_by_long_name(arrival_airport_name)
  end
  </code></pre>
  
  <p>The problem is, however, that when the user enters the name of an airport that does not exist in the database, the commit fails because the ID of either airport is <code>nil</code>. Great. What's not great, however, is that this validation failure is not reflected on the form because technically, it's the input for another field:</p>
  
  <pre><code>validates :departure_airport, :arrival_airport presence: true
  
  attr_accessor :departure_airport_name, :arrival_airport_name
  
  &lt;%= f.input :departure_airport_name %&gt;
  &lt;%= f.input :arrival_airport_name %&gt;
  </code></pre>
  
  <p>Is this even the way to properly go about, transforming the name of the airport into an ID in the <code>before_validation</code> callback? And if so, how can I get the validation errors to show up on the virtual name attribute of the airport?</p>