In Rails 4.1, how to find records by enum symbol?

Abdulaziz picture Abdulaziz · Aug 3, 2014 · Viewed 25.3k times · Source

Assume I have this model:

class Conversation < ActiveRecord::Base
  enum status: [ :active, :archived ]
end

How can I find all active conversations without using the numeric value of the enum or without having to iterate over each conversation?

I tried doing Conversation.where(status: :active), but it didn't yield any results.

The only solution comes to mind is to iterate over all conversations and select the active ones, but it doesn't look like a good solution.

Conversation.all.select {|conversation| conversation.active? }  

Is there anything I can do about this?

Answer

Kensuke Naito picture Kensuke Naito · Mar 19, 2015

ActiveRecord::Enum provides scopes based on its values.

Just try:

Conversation.active

or

Conversation.archived

Of course, you can create your own scopes as Kyle Decot mentioned.