我试图为4个用户播种数据库。每个用户都有has_one个人资料和has_many todo_lists。 用户模型:
class User < ActiveRecord::Base
has_one :profile, dependent: :destroy
has_many :todo_lists, dependent: :destroy
has_many :todo_items, through: :todo_lists, source: :todo_items
end
这是我的种子文件
User.destroy_all
user_list = [
["Carly", "Fiorina", "female", 1954],
["Donald", "Trump", "male", 1946],
["Ben", "Carson", "male", 1951],
["Hillary", "Clinton", "female", 1947]
]
user_list.each do |fname, lname, gender, byear|
{
User.create!(username: lname, password_digest: "xyz")
User.profile.create! (first_name: fname, last_name: lname, gender: gender, birth_year: byear )
User.todo_list.create!(list_name: "temp", list_due_date: 1.year.from_now);
}
end
我收到意外错误的tLABEL指向用户名:lname。我创建用户表的迁移是:
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :username
t.string :password_digest
t.timestamps null: false
end
end
end
答案 0 :(得分:1)
您不应在do-end块中使用括号。试试这个:
user_list.each do |fname, lname, gender, byear|
user = User.create!(username: lname, password_digest: "xyz")
user.create_profile!(first_name: fname, last_name: lname, gender: gender, birth_year: byear )
user.todo_lists.create!(list_name: "temp", list_due_date: 1.year.from_now);
end