播种嵌套模型,重复键错误

时间:2015-06-22 14:17:45

标签: ruby-on-rails ruby ruby-on-rails-4

我有两个相关的模型

锻炼:

has_many :exercises, dependent: :destroy
accepts_nested_attributes_for :exercises, 
                              :reject_if => :all_blank,
                              :allow_destroy => true

锻炼:

belongs_to :workout

锻炼控制器有以下参数:

params.require(:workout).permit(:name, exercises_attributes: [:id,:name,:reps,:sets,:weight])

这是我的seed.rb文件

5.times do |i|
  Workout.create(name: i, exercises_attributes: [ 
                                              name: 'Bench Press',
                                              reps: 5, 
                                              sets: 5, 
                                              weight: 200.0],
                      exercises_attributes: [ 
                                              name: 'Squat',
                                              reps: 5, 
                                              sets: 5, 
                                              weight: 100.0])
end

当我运行rake db:reset时出现以下错误:

~/db/seeds.rb:14: warning: duplicated key at line 19 ignored: :exercises_attributes

结果是Squat练习被添加并且Bench Press练习被忽略。知道如何解决这个问题,以便创造两者吗?

1 个答案:

答案 0 :(得分:0)

您收到重复键错误,因为您在Workout.create来电中指定了两次。

尝试只发送一次,但是使用哈希数组,以便将两个练习放入同一个数组中:

5.times do |i|
  Workout.create(name: i, exercises_attributes: [ 
    {
      name: 'Bench Press',
      reps: 5, 
      sets: 5, 
      weight: 200.0
    },
    {
      name: 'Squat',
      reps: 5, 
      sets: 5, 
      weight: 100.0
    }]
  )
end