2017-01-28 2 views
1

私のデータベースに偽のデータをシードしようとしています。私は各プロスペクトを1人のユーザに所属させたい。私のシードはユーザーを作成しますが、プロスペクトを作成することはできません。理由はわかりません。ループにhas_oneが失敗したループをシードします

User.destroy_all 
Prospect.destroy_all 

50.times do 

    u = User.new 
    u.email = Faker::Internet.email 
    u.password = "password" 
    u.first_name = Faker::Name.first_name 
    u.last_name = Faker::Name.last_name 
    u.save 

end 

users = User.all 
puts users 

users.each do |user| 
    p = Prospect.new 
    p.id = user.id 
    p.parent_first_name = user.first_name 
    p.parent_last_name = user.last_name 
    p.student_first_name = Faker::Name.first_name 
    p.save 
end 

はここ

# prospect.rb 
class Prospect < ApplicationRecord 
    belongs_to :user 

    def full_parent_name 
    name = "#{parent_first_name.capitalize} #{parent_last_name.capitalize}" 
    end 

end 

# user.rb 
class User < ApplicationRecord 
    has_one :prospect 

... lots of devise and Oauth stuff 
end 

マイプット文がUser.allが50人のユーザーが私は私の問題はbelongs_toを作成しようとしていることを考える発見されていることを示して私のユーザーと展望モデルだとhas_oneが問題です。私はそれを別の方法で扱うべきですか?

答えて

2

これは間違っているになります。

p.id = user.id 

あなたはあなたの製品は、あなたのユーザーと同じIDを持っている必要はありません。書くことができる

p.user = user 

しかし、

代替:

代わり

p = Prospect.new 
    p.user = user 
    p.parent_first_name = user.first_name 
    p.parent_last_name = user.last_name 
    p.student_first_name = Faker::Name.first_name 
    p.save 

のあなただけ書くことができる:あなたの見通しは、ユーザーに属しているので

user.create_prospect(student_first_name: Faker::Name.first_name) 

、それがデータベース内の同じ情報を保持するべきではありませんそのユーザーでdelegateを使用するか、parent_first_nameuser.first_nameと定義して、DBに書き込むことはできません。

+0

ありがとうございました。これはまさに私の問題でした。 – aisflat439

関連する問題