jeffmaher
jeffmaher

Reputation: 1902

How to compare an enum model attribute in a controller?

I have the following model object:

class ModelObj < ActiveRecord::Base
  enum type: [:value_a, :value_b]
end

In my controller, I want to check the enum type attribute's value, but not sure how. What is the syntax for a comparison of an enumerable value in a controller?

Here's some code from a controller that doesn't work:

class SomeController < ApplicationController
  def index
    m = ModelObj.find(...)
    if m.type == :value_a
      # do this ...
    end
  end
end

Upvotes: 8

Views: 14277

Answers (2)

Chris
Chris

Reputation: 2597

Here's what I have done to get it working:

class SomeController < ApplicationController
  def index
    m = ModelObj.find(...)
    if (ModelObj.types[m.type] == ModelObj.types[:value_a])
      # do this ...
    end
  end
end

You can see it as the current last example at http://edgeapi.rubyonrails.org/classes/ActiveRecord/Enum.html:

Conversation.where("status <> ?", Conversation.statuses[:archived])

But the issue is that it's an ordinal value whereas the m.type is the string value.

Upvotes: 5

Buck Doyle
Buck Doyle

Reputation: 6397

According to the ActiveRecord::Enum documentation, you can access the enum value in various ways. Some examples:

m.type     # => 'value_a'
m.value_a? # => true
m.value_b? # => false

You presented controller code you said “doesn’t work”, could it be that you need to use string comparison instead of symbols?

Upvotes: 16

Related Questions