I am running Ruby (1.9.3) on Rails (3.2.0) and having a problem with the validation of virtual attributes.
I have a Flight
model that represents a flight which, among others, has an attributes that represents the airport of departure and arrival.
Because the select
for selecting an airport is potentially huge, I opted to go for an autocomplete solution, which is working perfectly fine. I am using a before_validation
callback to properly populate the actual ID of the airport:
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 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 nil
. 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:
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 the way to properly go about, transforming the name of the airport into an ID in the before_validation
callback? And if so, how can I get the validation errors to show up on the virtual name attribute of the airport?
I think you are going the right way with the before_validation
callback.
You can validate virtual attributes like every normal attribute. So all you need is just some validation in the model. Try this:
validates :departure_airport, presence: true
validates :arrival_airport, presence: true
this should add an error to the objects errors and the error should be displayed in your form...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With