Reputation: 343
The following code that is inserting new rows correctly if people
isn't found. If people
is found I want it to update existing row and also the import_id
but the update isn't working. So basically if a new import contains the same data in people
I want to just update import_id
.
people
has name age
.
Person.transaction do
people.flatten.each do |people|
Person.create_with({ import_id: import.id, **people }).find_or_create_by(**people)
end
end
Upvotes: 0
Views: 57
Reputation: 5852
To restate the requirements, if an item in people
matches a Person
by name
and age
, update that person's import_id
. If that item in people
does not match Person
by name
and age
, create a new Person
and set the import_id
.
This should do what you're looking for.
Person.transaction do
people = [{ name: 'Tom', age: 20 }, { name: 'Jerry', age: 20 }]
people.flatten.each do |person|
Person.find_or_create_by(name: person[:name], age: person[:age])
.update_attributes(import_id: import.id)
end
end
Find or create the person by the desired attributes, and then update the import_id
on the new or existing record.
Upvotes: 1