ruby on rails - find_or_create from array -


i have array of 2 airport structs , need check if each exists already, and, if not, create it. unique key each airport :iata code.

when created or found need add both airports @trip

airports = [departure_airport, arrival_airport]  airports.each |a|   airport.where(iata: a.iata).first_or_create |airport|     unless airport.present?       air = airport.create(a.to_h)       @trip.airports << air     else       @trip.airports << airport     end   end end 

what missing? creates airport not pass variables a.to_h it.

for handling of scenario airport exists can rearrange code this:

airport = airport.where(iata: a.iata).first_or_create(a.to_h) # airport either first airport found, # or new 1 created depending on if 1 existed or not # either way can added @trip @trip.airports << airport 

Comments

Popular posts from this blog

facebook - android ACTION_SEND to share with specific application only -

python - Creating a new virtualenv gives a permissions error -

javascript - cocos2d-js draw circle not instantly -