SimonW
SimonW

Reputation: 6423

Rails: Most efficient way to check if a new record already exists in DB

Lets say I have a model Product.

Once in a while I get a file containing new products, the issue is that some of them may already have been entered into the DB.

The data doesn't contain any unique key and the can come structured differently with different fields. What I can do is select from the DB according to all the data I have and if a product is found, not to save the one from the file.

Product.where(:name => p.name, :desc => p.desc, :source => "some source", [more fields])

So my question is if there is a better rails way to check if the record already exists?

Inserting to fail on some unique key, isn't such a good idea IMO but can work too.

Upvotes: 1

Views: 1103

Answers (1)

Dougui
Dougui

Reputation: 7232

You can use the exist? function like this :

if Product.where(:name => p.name, :desc => p.desc, :source => "some source", [more fields])
  # do something
else
  # do something else
end

You can also use the find_or_create_by if your goal is to create a new record if it does not exist like this :

Product.find_or_create_by(:name => p.name, :desc => p.desc, :source => "some source", [more fields])

Upvotes: 3

Related Questions