我正在尝试创建一个rake任务来填充我的数据库。我需要创建1个用户,其中包含一组特定的deatails和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
答案 0 :(得分: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