現在seeds.rb
ファイルを利用して初期データを作成していますがうまくいきません(m_ m)
わかる方がいらっしゃれば教えていただきますようよろしくお願いいたします(m _m)
###エラー内容
bundle exec rake db:seed
コマンドを実行すると下記のエラーが発生します
bash
1NoMethodError: undefined method `<<' for nil:NilClass
###期待する動作
- 作成されるレコードをインスタンス変数に順次追加していきたい
(後の処理で利用、加工しやすくしたいため)
###動作環境
Ruby:2.4.5
Ruby on Rails: 4.2.11
MySQL: 5.7.18
###参考サイト
###わからないこと
seeds.rbファイルではactiverecordが使えるかわからない?
###該当のソースコード
ruby
1# db/seeds.rb 2# item data 3item_count = 0 410.times do 5 rand(7..23).times do 6 item_count += 1 7 @items << Item.create!( 8 name: "商品-#{(item_count + 1).to_s}", 9 price: rand(4000..300000), 10 category_id: (1..10) 11 ) 12 end 13end 14 15@highprice_items = @items.where(‘price >= ?’, 200000)
In the first place, I am afraid that your coding is not very appropriate as logic to write in a seed file. Launching this seed file many times should creates a great amount of 'item' objects that you wouldnt want to use. Better appropriate for seed file you might code it to add 'if @items.empty?', 'if @items.count < maxvalue' or something like that after getting '@items=Item.all'.
回答1件
あなたの回答
tips
プレビュー