Dofs
Dofs

Reputation: 19207

ActiveRecord giving wrong results in Rake task

I have created my first Rails Rake task which imports some data. It uses the URL to identify if the page needs to be updated or inserted. I am however having som really weird issue with some records being inserted multiple times instead, instead of just being updated.

My query looks like this:

existingCompany = Company.find_by_external_link(company.external_link)

I then look at

existingCompany.nil?

to see if the record needs to be created or updated. Some of the companies are not found by active record even though the external link exists. I have tried to print out the url and then look in the database (I use PostgreSQL) and it finds it correctly. The even weirder thing is that it doesn't happen to all records, only a few of them.

Anyone got an idea what might make ActiveRecord believe that a record doesn't exist?

Upvotes: 0

Views: 77

Answers (1)

hwatkins
hwatkins

Reputation: 1416

You don't give a lot of information, but a couple of things to try:

  1. How is company.external_link getting set? Either in the debugger or a simple puts can tell you if it is what you think. For example "http://www.ups.com/" != "https://www.ups.com/" != "http://www.ups.com"
  2. You may need to be consistant on capitalization or removing white space in company.external_link (.downcase, .strip)

Another thing to keep in mind is ActiveRecord creates a method Company.find_or_create_by_external_link which will do this in one step

Upvotes: 1

Related Questions