2017-02-23 97 views
0

我想用4個用戶種子數據庫。每個用戶擁有has_one個人資料和has_many todo_lists。 用戶模式:種子數據庫rails belongs_to

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指向用戶名:L-NAME。我創建用戶表的遷移過程如下:

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 

回答

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 
+0

是的,這是真的謝謝你的收穫。我認爲問題可能是我無法通過用戶創建配置文件。也許我必須創建一個配置文件,然後將其分配給用戶? – leenyburger

+0

您需要創建用戶實例的配置文件和todo_lists,而不是用戶類。我已經更新了我的答案以反映這一點。請記住,您的Profile和TodoList模型應該有一個外鍵將它們鏈接回給用戶。 – eiko

+0

現在我得到一個NoMethodError未定義的方法創建! – leenyburger