0

I'm currently in the process of creating a seeds file in my app and wanted to ensure that no duplicates were created using find_or_create_by suggested in this post. I'm using find_or_create_by_name but get this error:

NoMethodError: undefined method `find_or_create_by_name' for #<Class:0x007fa9680cb688>

This is what I'm using in the seeds file

Genre.find_or_create_by_name([
    {name: "Alternative"}, 
    {name: "Country"}, 
    {name: "Electronic"}
    ])

Also worth asking. If I had a uniqueness validator for a model's name would find_or_create_by still be necessary?

Community
  • 1
  • 1
Carl Edwards
  • 13,826
  • 11
  • 57
  • 119

2 Answers2

6

Newer versions of Rails use a slightly different syntax:

Genre.find_or_create_by(name: 'Alternative')

find_or_create_by does not support adding multiple records at a time so you'll have to construct an array of hashes and call find_or_create_by mutliple times:

hashes = [
  {name: "Alternative"}, 
  {name: "Country"}, 
  {name: "Electronic"}
]

hashes.each do |hash|
  Genre.find_or_create_by(hash)
end
infused
  • 24,000
  • 13
  • 68
  • 78
1

Alternatively, you could use something like this:

User.where(name: "Alice").first_or_create

This will return the first user with the name "Alice", or if there isn't one it'll create and return a new user with name "Alice".

This doesn't mean you can't have multiple users with the name "Alice", because if they were in the database before, you'll only find the first one.