I have a Workout model that looks like this:
class Workout < ApplicationRecord
belongs_to :user
validates :date, :kind, presence: true
validates :template, inclusion: { in: [true, false] }
enum kind: { other: 0, swim: 1, bike: 2, run: 3 }
has_many :comments, as: :commentable
end
In my view, I iterate through all workouts like this:
td
.row
.col-md-6
= day.to_formatted_s(:short)
.col-md-6.text-right
= link_to 'Add +', new_team_user_workout_path(date: day, athlete: @athlete)
- unless @workouts[day].blank?
- @workouts[day].each do |workout|
= link_to team_user_workout_path(@team, current_user, workout, athlete: params[:athlete]) do
.workout
.workout-kind.text-semibold
= workout.kind.capitalize
- unless workout.distance.blank?
.workout-spec.text-light
| Distance:
|
= workout.distance/1000
| km
- unless workout.duration.blank?
.workout-spec.text-light
| Duration:
|
= workout.duration/60
| mins
If enum is 'swim' I'd like to add a class to Workout like this: Workout.swim. If enum is 'bike' the Workout.bike class should be appended, so I can change the background color.
What is best practice for doing this in Rails?
Thanks.
You can check the enum by using the "interrogative" way object.enum?, so you could do:
.workout{ class: ('swim' if workout.swim?) }
In case the workout isn't a swim, it won't print anything.
If you have a class defined for each possible enum, then you could do also:
.workout{ class: workout.kind }
This would work in case the class swim has been defined, and it takes the same name as the enum.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With