在一个控制器中创建两个对象并在Rails

时间:2016-01-24 21:24:13

标签: ruby-on-rails

上下文

我正在制作锻炼应用程序,而且我无法连接两个模型,锻炼和锻炼设备。 Workout包括exercise_idsession_idworkout_equipment_idWorkout_Equipment是一个equipment_id和一个重量。锻炼/新的看起来像这样
enter image description here

守则

Workout_equipment不是我希望别人手动制作的东西,我希望在创建Workout时创建它,所以我有类似的东西

def create
   @workout_equipment = WorkoutEquipment.create(workout_equipment_params)
   @workout = Workout.create(workout_params)
end

def workout_equipment_params
   params.require(:workout_equipment).permit(:workout_id, :equipment_id, :weight)
end

def workout_params
   params.require(:workout).permit(:exercise_id, :session_id, :workout_equipment_id) 
end

相关模型(似乎)具有所有必要的外键。 Workout_equipment首先被打包,我希望随后根据练习和会话参数创建Workout,以及新创建的Workout_equipment ID。

问题

这是我点击提交时发生的事情:

 Parameters: {"utf8"=>"✓", "authenticity_token"=>"RjL7oiO0Bk028VXBbwVDmzSAvDIud5aWzGkJ4nMKn3qOj9QOUpowdMYNJaUsPy4nuG2o0xgpkF/uHXzhs2U6bw==", "workout"=>{"exercise_id"=>"4", "session_id"=>"3"}, "workout_equipment"=>{"equipment_id"=>"4", "weight"=>"9001"}, "commit"=>"Create Workout"}
   (0.1ms)  begin transaction
  SQL (0.2ms)  INSERT INTO "workout_equipments" ("equipment_id", "weight", "created_at", "updated_at") VALUES (?, ?, ?, ?)  [["equipment_id", 4], ["weight", 9001.0], ["created_at", "2016-01-24 18:24:16.696192"], ["updated_at", "2016-01-24 18:24:16.696192"]]
   (7.8ms)  commit transaction
   (0.0ms)  begin transaction
  SQL (0.2ms)  INSERT INTO "workouts" ("exercise_id", "session_id", "created_at", "updated_at") VALUES (?, ?, ?, ?)  [["exercise_id", 4], ["session_id", 3], ["created_at", "2016-01-24 18:24:16.705751"], ["updated_at", "2016-01-24 18:24:16.705751"]]
   (5.7ms)  commit transaction
   (0.0ms)  begin transaction
   (0.0ms)  commit transaction

如您所见,Workout_equipment_id未插入Workout对象,这是有道理的,因为它不在参数中的任何位置。 create方法只接受一个参数,因此如果我想将id放在某个地方,它必须包含参数。

所以在这样的情况下,我必须在create方法中添加一些额外的参数,如何将我的参数绑定到表单?

模型

class WorkoutEquipment < ActiveRecord::Base

  belongs_to :workout
  has_many :equipment

end

class Workout < ActiveRecord::Base

  belongs_to :exercise
  belongs_to :session
  has_many :workout_equipments

end

1 个答案:

答案 0 :(得分:1)

您可以稍微延迟创建对象。

@workout = Workout.new(workout_params)
@workout.workout_equipment_id = @workout_equipment.id
@workout.save