bundle exec rake db:populate>> rake aborted - 验证失败

时间:2012-05-22 11:15:47

标签: ruby-on-rails ruby-on-rails-3 validation rake ruby-on-rails-3.2

我目前正在浏览RoR指南,而且我被困在......

“将以下/关注者关系添加到示例数据中。”

以下是可以使用的代码:sample_app/lib/task/sample_data.rake

namespace :db do
desc "Fill database with sample data"
task populate: :environment do
    make_users
    make_microposts
    make_relationships
  end
end

def make_users
 admin = User.create!(name:     "Example User2",
                     email:    "example2@railstutorial.org",
                     password: "foobar",
                     password_confirmation: "foobar")
admin.toggle!(:admin)
99.times do |n|
 name  = Faker::Name.name
 email = "example-#{n+1}@railstutorial.org"
 password  = "password"
 User.create!(name:     name,
              email:    email,
              password: password,
              password_confirmation: password)
  end
end

def make_microposts
  users = User.all(limit: 6)
  50.times do
    content = Faker::Lorem.sentence(5)
    users.each { |user| user.microposts.create!(content: content) }
  end
end

def make_relationships
  users = User.all
  user  = users.first
  followed_users = users[2..50]
  followers      = users[3..40]
  followed_users.each { |followed| user.follow!(followed) }
  followers.each      { |follower| follower.follow!(user) }
end

当我rake db:reset我的数据库重置没有问题。

当我rake db:populate发生错误时说明:

 rake aborted!
 Validation failed: Follower can't be blank`

所以我检查了我的数据库,所有的表都填充了除“关系”表之外的任何想法或建议?我非常确定代码def making_relationships确实存在问题。希望任何人都能解决这个问题..

-Marc

1 个答案:

答案 0 :(得分:3)

由于您在.create!UserMicropost)等模型上调用user.microposts,因此其中一个会抛出上述错误。

请发布这些模型的代码,以便我们更具体地回答。

你仍然可以自己调试问题。只需点击项目根目录中的rails c,然后尝试使用您在rake任务中尝试的相同属性创建实例:

$ rails c

$ user = User.create!(name:     name,
                      email:    email,
                      password: password,
                      password_confirmation: password)

$ micropost = user.microposts.create!(content: "Hello, cruel world!")

# by this step you should already see some errors raised; if that's not sufficient,
# call the following methods to figure out what model suffers the validation error
user.errors.full_messages
micropost.errors.full_messages

无论如何,这是不满意的验证。仔细检查您是否传递了使用shebang create!创建模型时传递的所有必需属性。具体检查哪个模型需要Follower(无论是什么)。