Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validation of virtual attributes in Ruby on Rails

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?

like image 885
Laurens Avatar asked Mar 17 '12 09:03

Laurens


1 Answers

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...

like image 182
klump Avatar answered Oct 03 '22 00:10

klump