首页 > 解决方案 > Rails 如何找到尚未与用户关联的不区分大小写的值?

问题描述

新手 Rails 开发人员在这里,所以请与我裸露。

我有一个名为成分的表,其中包含一个标题字段和一个与用户的关联。一个用户可以有很多成分。

我想查询数据库以获取用户尚不可用的成分。

我尝试用 Rails 做这样的事情:

@ingredients = current_user.ingredients
@community_ingredients = Ingredient.all.excluding(@ingredients).pluck(:title, :id)

但问题是这仍然返回相同的值,只是大小写不同。

我怎样才能达到这个结果?

标签: ruby-on-railsruby

解决方案


尝试以下查询。

@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)

所以基本上我们需要在相同的情况下转换列值和匹配列表。所以我们已经转换为小写。

这是它在我的本地系统中的外观,只需确保它以这种方式工作即可。

在此处输入图像描述


推荐阅读