上下文
我正在制作锻炼应用程序,而且我无法连接两个模型,锻炼和锻炼设备。 Workout
包括exercise_id
,session_id
和workout_equipment_id
。 Workout_Equipment
是一个equipment_id和一个重量。锻炼/新的看起来像这样
守则
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
答案 0 :(得分:1)
您可以稍微延迟创建对象。
@workout = Workout.new(workout_params)
@workout.workout_equipment_id = @workout_equipment.id
@workout.save