1

我目前正在浏览 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确切地说。希望有人对此有解决方案..

-马克

4

1 回答 1

3

由于您调用的是和( ) 之.create!类的模型,因此它是其中之一抛出提到的错误。UserMicropostuser.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(无论是什么)。

于 2012-05-22T11:29:24.737 回答