Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 763
jeffmaher Avatar asked May 20 '14 04:05

jeffmaher


2 Answers

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?

like image 139
Buck Doyle Avatar answered Oct 09 '22 14:10

Buck Doyle


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.

like image 29
Chris Avatar answered Oct 09 '22 14:10

Chris