我有一组用户锻炼。锻炼包含一系列练习。每个练习都有一个类别。
我想迭代训练集合并按练习类别分组。
让我失望的是exercise_workouts
是一个连接模型。例如:
#<ExerciseWorkout id: 50, exercise_id: 14, workout_id: 42, description: nil, created_at: "2013-03-12 08:15:17", updated_at: "2013-03-12 08:15:17", user_id: nil>
.exercises
%h1.exercise-type-title Lifting Exercises
= render @workout.exercise_workouts
我想通过练习通过可用类别渲染@workout.exercise_workouts
部分组。所以我会看到像
.exercises
%h1.exercise-type-title Lifting Exercises
= render @workout.exercise_workouts (lifting)
%h1.exercise-type-title Running Exercises
= render @workout.exercise_workouts (running)
不知道怎么回事?并且也不希望对每个类别进行硬编码,只列出通过智能迭代器可用的内容。
答案 0 :(得分:1)
你可以尝试以下(我不确定我是否有基于exercise_workouts
类的部分正确的名称
@workout.exercise_workouts.group_by(&:category).each do |category, exercises|
= render partial: '/exercise_workouts/exercise_workout', collection: exercises, locals: { category: category }
更新:访问exercise
您可以将循环更改为
@workout.exercise_workouts.group_by { |ew| ew.exercise.category }.each do |category, exercises|
= render partial: '/exercise_workouts/exercise_workout', collection: exercises, locals: { category: category }
或者您可以在exercise_workout模型
上委托category属性进行练习#exercise_workout.rb
delegate :category, to: :exercise
仍然使用第一个版本。就个人而言,我更喜欢第二种解决方案。