Home Change class color based on enum
Reply: 1

Change class color based on enum

Andy Published in 2018-02-12 10:49:24Z

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

In my view, I iterate through all workouts like this:

      = day.to_formatted_s(:short)
      = 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.kind.capitalize
          - unless workout.distance.blank?
              | Distance:
              | &nbsp;
              = workout.distance/1000
              | &nbsp;km
          - unless workout.duration.blank?
              | 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?


Sebastian Palma
Sebastian Palma Reply to 2018-02-12 11:06:49Z

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.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.297291 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO