在 ActiveRecord 中按位掩码搜索

发布于 2024-09-12 01:43:31 字数 284 浏览 0 评论 0原文

我有一个带有位掩码字段的用户表,其中包含权限掩码。在本地,我可以通过执行位掩码 (UserPermissions&Perm)==Perm 来确定用户是否具有特定权限。但是,我希望能够发出 find_by_mask 或类似的东西,也许使用 :conditions,但我似乎不知道如何查询数据库检索具有匹配权限掩码的用户列表。

使用 ActiveRecord 有什么想法吗?

具体来说,这必须使用 sqlite 和 postgres 来工作

I have a users table with a bitmask field that has a permissions mask in it. Locally, I can determine whether a user has a certain permission by doing a bitmask (UserPermissions&Perm)==Perm. However, I want to be able to issue a find_by_mask or something similar, perhaps using a :conditions, but I can't seem to find out how I can query the database to retrieve a list of users with a matching permission mask.

Any ideas using ActiveRecord?

Specifically this must work using sqlite and postgres

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

爺獨霸怡葒院 2024-09-19 01:43:31

在我看来,明智的做法是将位掩码字段分解为一系列布尔字段。在关系数据库中存储位掩码与在字段中存储分隔列表相差不远——它是边界非规范化。

也就是说,您可以在 SQL 查询中使用 & 进行按位 AND 操作。运算符,所以你可以说:

User.where('permissions & ? > 0', Perm)

The sane thing to do, in my opinion, would be to break out your bitmask field into a series of boolean fields. Storing bitmasks in a relational database is not that far off from storing delimited lists in a field -- it's borderline denormalization.

That said, you can use a bitwise AND in your SQL queries with the & operator, so you can say:

User.where('permissions & ? > 0', Perm)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文