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
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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With