find_or_create from array

时间:2015-06-12 20:19:56

标签: ruby-on-rails ruby ruby-on-rails-4

我有两个机场结构的数组,需要检查每个结构是否已存在,如果没有,则创建它。每个机场的唯一密钥是:iata代码。

创建或找到后,我需要将Airports添加到@trip

airports = [departure_airport, arrival_airport]

airports.each do |a|
  Airport.where(iata: a.iata).first_or_create do |airport|
    unless airport.present?
      air = airport.create(a.to_h)
      @trip.airports << air
    else
      @trip.airports << airport
    end
  end
end

我错过了什么?这会创建机场但不会传递a.to_h中的变量。

2 个答案:

答案 0 :(得分:2)

对于机场已经存在的场景的处理,你可以重新安排代码如下:

airport = Airport.where(iata: a.iata).first_or_create(a.to_h)
# airport will now either be the first airport that was found,
# or the new one that was created depending on if one existed or not
# either way it can then be added to @trip
@trip.airports << airport

答案 1 :(得分:1)

您不必对此进行测试:unless airport.present?,机场将始终存在,因为first_or_create方法会返回记录或创建新记录。

而不是air = airport.create(a.to_h)写:airport.to_h = a.to_h

试试这个:

airports.each do |a|
    Airport.where(iata: a.iata).first_or_create do |airport|
        airport.to_h = a.to_h
        @trip.airports << airport
      end
    end
  end