简体   繁体   中英

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?

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

按照enum文档,您应该能够自动使用enum定义的范围:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM