根据枚举

时间:2018-02-12 10:49:24

标签: ruby-on-rails ruby class enums

我有一个看起来像这样的锻炼模型:

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

在我看来,我会遍历所有类似的训练:

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

如果enum是游泳&#39;我想在Workout中添加一个类:Workout.swim。如果enum是&#39; bike&#39;应该附加Workout.bike类,这样我就可以改变背景颜色。

在Rails中执行此操作的最佳做​​法是什么?

感谢。

1 个答案:

答案 0 :(得分:1)

您可以使用“疑问”方式object.enum?来检查枚举,以便您可以这样做:

.workout{ class: ('swim' if workout.swim?) }

如果锻炼不是游泳,它将不会打印任何东西。

如果您为每个可能的枚举定义了一个类,那么您也可以这样做:

.workout{ class: workout.kind }

如果已经定义了类游泳,它将起作用,并且它与枚举名称相同。