Validating virtual attributes in Ruby on Rails

I am running Ruby (1.9.3) in Rails (3.2.0) and have a problem with validating virtual attributes.

I have a Flight model, which is a flight that, among other things, has attributes that represent the airport of departure and arrival.

Since the select for choosing an airport is potentially huge, I decided to go for an autocomplete solution that works fine. I use the before_validation to populate the actual airport id correctly:

 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 

The problem, however, is that when a user enters the name of an airport that is not in the database, the commit is not executed because the identifier of any airport is nil . Fine. However, it is not the biggest that this verification failure does not affect the form, because technically this is an input for another field:

 validates :departure_airport, :arrival_airport presence: true attr_accessor :departure_airport_name, :arrival_airport_name <%= f.input :departure_airport_name %> <%= f.input :arrival_airport_name %> 

Is this even a way to make good use of converting the airport name to identifier in the before_validation ? And if so, how can I get validation errors to display the airport virtual name attribute?

+7
source share
1 answer

I think you are going right with the before_validation .

You can check virtual attributes like every normal attribute. Thus, all you need is just some validation in the model. Try the following:

 validates :departure_airport, presence: true validates :arrival_airport, presence: true 

this should add an error to the object errors, and the error should appear in your form ...

+4
source

All Articles