Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change class color based on enum

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:
              | &nbsp;
              = workout.distance/1000
              | &nbsp;km
          - unless workout.duration.blank?
            .workout-spec.text-light
              | Duration:
              | &nbsp;
              = workout.duration/60
              | &nbsp;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.

like image 457
Andy Avatar asked Dec 17 '25 13:12

Andy


1 Answers

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.

like image 52
Sebastian Palma Avatar answered Dec 20 '25 09:12

Sebastian Palma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!