【问题标题】:Why is rake db:seed not behaving as expected?为什么 rake db:seed 没有按预期运行?
【发布时间】:2012-10-18 04:35:12
【问题描述】:

我正在尝试以一种非常特殊的方式为我的数据库播种。这是我的 /db/seeds.rb 文件:

# 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

那么问题是什么?好吧,当我检查我的数据库时,只创建了第一个关键字,关键字的 message1 字段如下所示:

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

什么时候应该是这样的:

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

我做错了吗?

【问题讨论】:

  • 出于兴趣:为什么所有内容都是双倍行距?
  • 我不知道,它不在我的编辑器中。我复制并粘贴,但并没有真正注意间距。
  • 好的。我给你修好了。您在哪里看到这个 message1 字段?您如何从数据库中检索该值?
  • 出于好奇,是create_on_avid,您已经定义了一个类方法。
  • 一个小建议,用keywords_ary.each_with_index代替keywords_ary.each

标签: ruby-on-rails rake seeding


【解决方案1】:
 Keyword.find_or_create_by_user_id

这看起来像是罪魁祸首,因为你正在做 find_or_create_by_user_id

所以第一次它会创建一个具有该 user_id 的对象,之后每次它都会获取相同的对象。

可以改成

Keyword.find_or_create_by_message1

【讨论】:

    【解决方案2】:

    我发现了我的方式的错误。在我的keywords_ary.each 循环中,使用Keyword.find_or_create_by_user_id 来创建我的每个关键字。问题是,每个关键字都有相同的user_id。所以在找到或创建第一个关键字后,循环退出。

    我将其更改为 Keyword.find_or_create_by_user_id_and_name 并没有正常工作。

    【讨论】:

      猜你喜欢
      • 2016-09-09
      • 1970-01-01
      • 1970-01-01
      • 2010-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-01
      • 2014-11-07
      相关资源
      最近更新 更多