Question

I am trying to seed my database in a very particular manner. Here is my /db/seeds.rb file:

# creates a school in a local database.
test_school = School.find_or_create_by_email(school_name: "Test School One", client_user_name: 'admin', client_password: 'Secretz1', fname: 'John', lname: 'doe', client_short_code: "72727", email: 'testemail@testemail.com')

# creates a user in local database
test_user = User.find_or_create_by_email(email: test_school.email, password: test_school.client_password, full_name: test_school.full_name, user_role: 'admin', school_id: test_school.id )

# creaate school via API
results = School.create_via_api test_school 

if results[0].to_i == 0
  test_school.update_attribute :client_number, results[2].split(" ").first
  SchoolMailer.registration_confirmation(test_user, test_school).deliver
else
  test_school.destroy
  test_user.destroy
end

# an array of keyword topics
keywords_ary = ["lunch", "schoolout?", "thenews", "holidays", "buses", "help"]
# create a keyword object for each topic in the above array
keywords_ary.each do |n|
  message = ""
  Array(1..5).each do |i|
    message += "#{i}. Test for @ts#{n}\n"
  end
  Keyword.find_or_create_by_user_id(
    name: "@ts#{n} test", keyword: "@ts#{n}", 
    message1: message, 
    user_id: test_user.id
    )
end

# create each of the keywords via API
test_user.keywords.each do |keyword|
  results = Keyword.create_on_avid keyword, test_user
  if results[0].to_i == 0
    #save the api id to the local database
    keyword.update_attribute :keyword_id, results[2]
  else
    keyword.destroy
  end
end

So what's the problem? Well, when I check my database only the very first keyword is created, and the message1 field for the keyword looks like this:

 --- - 1 - 2 - 3 - 4 - 5

when it should look like this:

1. this is a test for @tslunch
2. this is a test for @tslunch
3. this is a test for @tslunch
4. this is a test for @tslunch
5. this is a test for @tslunch

Am I doing something wrong?

Was it helpful?

Solution

 Keyword.find_or_create_by_user_id

This looks like the culprit, coz you are doing find_or_create_by_user_id

So the first time it will create an object with that user_id and after that everytime it will fetch the same object.

may be change that to

Keyword.find_or_create_by_message1

OTHER TIPS

I've spotted the error of my ways. In my keywords_ary.each loop, used Keyword.find_or_create_by_user_id to create each of my keywords. the problem is that, each keyword has the same user_id. So after the first Keyword is found or created, the loop exited.

I changed it to Keyword.find_or_create_by_user_id_and_name and no it works finely.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top