i cant code
i cant code

Reputation: 343

I want to add a row if not found, update if it is found

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

Answers (1)

Jake Worth
Jake Worth

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.

find_or_create_by docs

Upvotes: 1

Related Questions