1

我正在尝试创建一个 rake 任务来填充我的数据库。我需要创建 1 个具有特定细节集的用户和 99 个其他随机生成的用户。所需的详细信息同时适用于两个模型,类似于具有嵌套属性的表单。我的模型使用 after_create 回调来创建用户并将其链接到团队。团队名称默认为用户名

我使用它产生错误的当前代码

sample_data.rake

namespace :db do
  desc "Fill database with sample data"
  task populate: :environment do
  user = User.create!(:profile_attributes => { name: Forgery::Name.full_name },
              email: "test@example.com",
              password: "123qwe",
              password_confirmation: "123qwe")
  99.times do |n|
      :profile_attributes => { name: Forgery::Name.full_name },
      email = Forgery::Internet.email_address
      password  = "password"
      user = User.create!(email: email,
                          password: password,
                          password_confirmation: password)
     end 
  end
end

依赖于嵌套属性的模型。

class User < ActiveRecord::Base
  after_create :set_user_on_team



  private
  def set_user_on_team
     self.create_owned_team(:name => self.profile.name ).users << self

  end

end

错误信息

rake aborted!
/lib/tasks/sample_date.rake:9: syntax error, unexpected tASSOC, expecting keyword_end
    :profile_attributes => { name:  Forgery::Name.full_name },
                        ^
/lib/tasks/sample_date.rake:9: syntax error, unexpected ',', expecting keyword_end
4

1 回答 1

1

我注意到99.times块中有一些语法错误。你可以这样尝试:

99.times do |n|
  profile_attributes = { name: Forgery::Name.full_name }
  email = Forgery::Internet.email_address
  password  = "password"
  user = User.create!(profile_attributes: profile_attributes, #my assumption
                      email: email,
                      password: password,
                      password_confirmation: password)
end 
于 2012-07-29T17:10:01.303 回答