1

I am creating a few records programmatically based on a users input and creating an array of records to import.

When I check the database I can see the relationship has been created if they are new records.

If one of the records already exists in the database I can see an entry of the following in the association table but I can also see the new records have been created in their respective table so they exist but the records ID is not being updated in the association table.

user_id: 1
keyword_id: null

but if I run the code for a second time it will add the relationship correctly.

This is my code

records_to_add = []

words.each do |word|
  keyword = Keyword.find_or_initialize_by(
    word:             word,
    device:           device,
  )
  records_to_add.push(keyword)
end

keywords_added = Keyword.import records_to_add, on_duplicate_key_ignore: true, validate: true

user.keywords << records_to_add

I think there is something wrong with this part of the code

user.keywords << records_to_add

It isn't creating the relationship correctly if one of the records already exists...

1 Answer 1

1

You are calling 'find_or_initialize_by' in your words loop, and then importing those records, which creates a new row in your Keyword table for all the new records.

So far, so good.

Then your script takes the first list (persisted and new records) and attempts to associate them to the user. At this point, it creates associations for existing Keyword records, but tries to create new Keyword records again for the ones that it just created in the import and associate those. These probably fail a unique validation at that point, and are not associated nor persisted.

That leaves you with just the unassociated but newly created records.

Sign up to request clarification or add additional context in comments.

1 Comment

So what do I need to do to fix it?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.