简体   繁体   English

Rails高级sql查询

[英]Rails advanced sql query

I have a model User thats has_many user_entitlements. 我有一个模型User hass has_many user_entitlements。 I want to get all of the users that have a preview attribute and no user entitlements. 我想让所有具有预览属性且没有用户权限的用户。

My code is currently: 我的代码目前是:

User.where("preview is not null").keep_if {|user| user.user_entitlements.empty?}

This is iterating through all of the users and seeing if they have any user entitlements. 这将迭代所有用户并查看他们是否拥有任何用户权利。

Is there a way I could do this in SQL to make it more efficient and avoid having to go through each user? 有没有办法在SQL中做到这一点,以提高效率,避免不得不通过每个用户?

You can use Arel to build a query leveraging NOT EXISTS . 您可以使用Arel构建一个利用NOT EXISTS的查询。

user_arel = User.arel_table
ue_arel = UserEntitlement.arel_table
User.where("preview is not null").where(
  UserEntitlement.where(ue_arel[:user_id].eq(user_arel[:id])).exists.not
)

I am making an assumption on your schema that UserEntitlement contains a user_id column. 我在您的架构上假设UserEntitlement包含user_id列。

Even simpler, you can use includes to force a LEFT JOIN, then check for NULL: 更简单的是,你可以使用includes来强制LEFT JOIN,然后检查NULL:

User.includes(:user_entitlements).
     where("users.preview IS NOT NULL AND user_entitlements.id IS NULL")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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