ruby-on-rails - Rails 如何找到尚未与用户关联的不区分大小写的值?
问题描述
新手 Rails 开发人员在这里,所以请与我裸露。
我有一个名为成分的表,其中包含一个标题字段和一个与用户的关联。一个用户可以有很多成分。
我想查询数据库以获取用户尚不可用的成分。
我尝试用 Rails 做这样的事情:
@ingredients = current_user.ingredients
@community_ingredients = Ingredient.all.excluding(@ingredients).pluck(:title, :id)
但问题是这仍然返回相同的值,只是大小写不同。
我怎样才能达到这个结果?
解决方案
尝试以下查询。
@community_ingredients = Ingredient.includes(:user).where("users.user_id = ?", current_user.id).where(users: { id: nil } ).pluck(:title, :id)
OR
Ingredient.includes(:user).where("users.user_id = ?", current_user.id).where(ingredients: {user_id: nil } ).pluck(:title, :id)
OR
Ingredient.includes(:user).where("users.user_id = ?", current_user.id).where(users: { ingredient_id: nil } ).pluck(:title, :id)
根据您的关联选择正确的查询,并随时建议我,以便我可以删除多余的查询。
很可能第一个或第二个查询会起作用,我强烈认为第三个可能不是这样。
假设这个不适合您,并且您希望拥有基于您的架构的解决方案。
@ingredients = current_user.ingredients.pluck(:title)
@community_ingredients = Ingredient.where.not("lower(title) IN (?)", @ingredients.map(&:downcase)).pluck(:title, :id)
所以基本上我们需要在相同的情况下转换列值和匹配列表。所以我们已经转换为小写。
这是它在我的本地系统中的外观,只需确保它以这种方式工作即可。
推荐阅读
- php - 如何在远程计算机上运行目标文件?
- javascript - 从 POSTman 发送 POST 请求与从 Android (Java) 发送 POST 请求不同吗?
- awk - 在awk中选择等于不同值的行
- r - 选择数字列名
- python - 使用python获取数据框中某些列(独立)的总数
- c# - 在 Windows 7 上使用带有 NSIS 的 Dotnet 失败
- node.js - 使用 Multer 和 Node 将多个文件上传到 mongoDB
- ssh - SSH Key 提示“ssh -Tv git@gitlab.tubit.tu-berlin.de”的密码
- android - Flutter:使用 InteractiveViewer 双击启用图像放大/缩小
- swift - 快速按顺序查找元素的计数?