1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class Garage < ActiveRecord::Base
  has_many :vehicles

  after_save :save_vehicles

  def new_vehicles=(new_vehicle_attributes)
    new_vehicle_attributes.each_pair { |vehicle_id, attributes|
        self.vehicles.build(attributes) unless attributes.delete.to_i == 1
    }
  end

  def existing_vehicles=(existing_vehicle_attributes)
    existing_vehicle_attributes.each_pair { |vehicle_id, attributes|
        if vehicle = self.vehicles.select { |i| i.id == vehicle_id.to_i }.first
            vehicle.attributes = attributes
        end
    }
  end

  private
    def save_vehicles
      self.vehicles.each { |i|
        if i.delete.to_i == 1
          i.destroy unless i.new_record?
        else
          i.save
        end
      }
    end
end

class Vehicle < ActiveRecord::Base
  belongs_to :garage

  attr_accessor :delete
end