如果我为训练创建新的练习,则我的字段member_id
为空。
工作原理
belongs_to :member
has_and_belongs_to_many :exercises
def add_exercise_with_name(exercise_name)
self.exercises << Exercise.find_or_create_by(name: exercise_name)
end
体育锻炼
has_and_belongs_to_many :workouts
belongs_to :member
运动控制器.erb
def create
@workout = current_user.workouts.find(params[:workout_id])
@exercise = @workout.add_exercise_with_name(exercises_params['name'])
redirect_to workout_path(@workout)
end
我该如何添加练习的成员?
最佳答案
将id作为额外参数传递给方法。
def add_exercise_with_name(exercise_name, member_id)
self.exercises << Exercise.find_or_create_by(name: exercise_name, member_id: member_id)
end
这有副作用。现在
find_or_create
调用将在查找练习时考虑member_id
。如果不需要,请使用create_with(member_id: member_id)
。self.exercises << Exercise.create_with(member_id: member_id).find_or_create_by(name: exercise_name)
此外,还可以使用块语法:
self.exercises << Exercise.find_or_create_by(name: exercise_name) do |exercise|
exercise.member_id = member_id
end