Abdulaziz
Abdulaziz

Reputation: 2211

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

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?

Upvotes: 48

Views: 28776

Answers (6)

Mirror318
Mirror318

Reputation: 12693

This works great:

Conversation.where("conversation.status = ?", Conversation.statuses[:active])

For some reason this does NOT work:

Conversation.where(status: :active) #searches for NULL
Conversation.where(status: 'active') #searches for status=0 no matter what the enum

Update

All the above statements work with Rails 5. Happy coding!

Upvotes: 48

6ft Dan
6ft Dan

Reputation: 2445

Conversation.where(status: Conversation.statuses[:active])

Upvotes: 8

Shifa Khan
Shifa Khan

Reputation: 779

Did you try Conversation.where(status: [:active, :archived]) ? As listed here.

Upvotes: 4

Kyle Decot
Kyle Decot

Reputation: 20835

ActiveRecord::Enum provides built-in scopes based on the values so you can simply do:

Conversation.active
Conversation.archived

Upvotes: 28

Kensuke Naito
Kensuke Naito

Reputation: 776

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.

Upvotes: 62

jasmo2
jasmo2

Reputation: 525

try this:

.enum :status => {:active => "active", :archived => "archived"ok_off => "took off"}

Upvotes: -8

Related Questions