In our Rails 3.2.13 app we need to query an API for Order data which has many associciated objects, and then store it in our database. Some records may already exist, so if they exist we want to update, if new then we want to create. We are importing thousands of records at a time.
I’ve been looking into the activerecord-import gem to help performance optimize this using the import method, and came up with the below code:
def add_details(order, tax_lines) tax_lines.each do |shopify_tax_line| taxlines_updated << Taxline.where(:order_id => order.id).first_or_initialize( :price => tax_line.price, :rate => tax_line.rate, :title => tax_line.title) end Taxline.import taxlines_updated, :validate => false end
The problem is, if the record already exists then it is not updated, it only updates the attributes if the record is new.
How can I get this to work like: “if found -> update attributes” or “if not found -> new” on each record?