ZK Zhao
ZK Zhao

Reputation: 21573

Rails: Enum query with multiple values

In edge API(http://edgeapi.rubyonrails.org/classes/ActiveRecord/Enum.html), we could use

Conversation.where(status: [:active, :archived])
Conversation.where.not(status: :active)

But now we can only use something like

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

Then, In Rails 4.1.8, How can I query :active and :archived at the same time?

Upvotes: 1

Views: 1519

Answers (1)

Arup Rakshit
Arup Rakshit

Reputation: 118289

Here is what you want :

Conversation.where(status: Conversation.statues.values_at(:active, :archived))

..The mappings are exposed through a class method with the pluralized attribute name, which return the mapping in a HashWithIndifferentAccess.

Demo :

[12] pry(main)> Pet.all
  Pet Load (0.5ms)  SELECT "pets".* FROM "pets"
=> [#<Pet id: 6, animals: 1, created_at: "2015-02-21 10:40:19", updated_at: "2015-02-21 10:40:19", name: "Tilly">,
 #<Pet id: 7, animals: 0, created_at: "2015-02-21 10:40:31", updated_at: "2015-02-21 10:40:54", name: "Xav">,
 #<Pet id: 5, animals: 1, created_at: "2015-02-19 18:27:28", updated_at: "2015-02-21 10:41:06", name: "Mua">]
[13] pry(main)> Pet.where(animals: Pet.animals.values_at(:dog))
  Pet Load (0.7ms)  SELECT "pets".* FROM "pets"  WHERE "pets"."animals" IN (0)
=> [#<Pet id: 7, animals: 0, created_at: "2015-02-21 10:40:31", updated_at: "2015-02-21 10:40:54", name: "Xav">]
[14] pry(main)> Pet.where(animals: Pet.animals.values_at(:cat))
  Pet Load (0.8ms)  SELECT "pets".* FROM "pets"  WHERE "pets"."animals" IN (1)
=> [#<Pet id: 6, animals: 1, created_at: "2015-02-21 10:40:19", updated_at: "2015-02-21 10:40:19", name: "Tilly">,
 #<Pet id: 5, animals: 1, created_at: "2015-02-19 18:27:28", updated_at: "2015-02-21 10:41:06", name: "Mua">]

But the below is more clean :-

Conversation.where(status: [:active, :archived])

Upvotes: 3

Related Questions