Qwertie
Qwertie

Reputation: 6573

Active record query enum column

I have a query that looks like this

where("user_id = ? OR privacy = ?", user_id, :public_activity)

And the enum

enum privacy: [:public_activity, :friends_activity, :private_activity]

:public_activity doesn't work in this query and just gets sent as a string. Is there any clean way to write this query without just using an integer which will be hard to understand when reading the query?

Upvotes: 0

Views: 91

Answers (2)

spickermann
spickermann

Reputation: 107067

Following the documentation of enum you should be able to use the scope that is defined by enum automatically:

Model.where(user_id: user_id).or(Model.public_activity)

Upvotes: 2

Roman Kiselenko
Roman Kiselenko

Reputation: 44370

You can use key in order to fetch integer, here is an example:

# app/models/user.rb
class Model < AR
  enum privacy: [:public_activity, :friends_activity, :private_activity]
end

Fetch status integer:

Model.privacies[:public_activity] => 0

The where method:

where("user_id = ? OR privacy = ?", user_id, Model.privacies[:public_activity])

Read documentation

Upvotes: 3

Related Questions