【问题标题】:Rails where.not skips some recordsRails where.not 跳过一些记录
【发布时间】:2015-10-18 16:30:29
【问题描述】:

我尝试获取除类别 [20,21,22] 之外的所有视频

这是我的查询

@cc = Video.joins(:categories).where.not(categories: { id: [20,21,22]})

但是当我这样做时@cc.find(113).categories 我明白了

#<ActiveRecord::Associations::CollectionProxy 
[#<Category id: 21, title: "music">, #<Category id: 22, title: "movies">,
#<Category id: 28, title: "collage">]>

我做错了什么?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 join activerecord associations


    【解决方案1】:

    试试这个,

    @cc = Video.includes(:categories).references(:categories).where.not(categories: { id: [20,21,22]})
    

    参考, https://robots.thoughtbot.com/activerecords-wherenot

    【讨论】:

    • 还是一样。我仍然可以在检索到的包含这些错误类别的集合中找到 ID 为 113 的视频
    • 你能告诉我触发的查询以及@cc.categories
    • 这是查询触发 SELECT "videos"."id" AS t0_r0, "videos"."id_string" AS t0_r1, "videos"."title" AS t0_r2, "videos"."duration" AS t0_r3, "videos"."thumbnail" AS t0_r4, "videos"."rating" AS t0_r5, "videos"."created_at" AS t0_r6, "videos"."updated_at" AS t0_r7, "categories"."id" AS t1_r0, "categories"."title" AS t1_r1 FROM "videos" 左外连接 "categories_videos" ON "categories_videos"."video_id" = "videos"."id" 左外连接 "categories" ON "categories"。 id" = "categories_videos"."category_id" WHERE ("categories"."id" NOT IN (20, 21, 22))
    • @cc.categories NoMethodError: undefined method `categories' for #<:activerecord_relation:0x007fbb4d9e0358>
    【解决方案2】:

    试试这个:

    array = [21,22,23]
    @cc = Video.joins(:categories).where("category.id not in (?)", array)
    

    编辑

    我认为我发现了问题。假设您的Video 模型与Category 存在has_many 关系。所以你应该这样做:

    class Video < ActiveRecord::Base
      has_many :categories
      has_many :excluded, -> (array) { where("id not in (?)", array) }, class_name: 'Category'
    end
    

    你这样称呼它:

    Video.find(113).excluded([21,22,23])
    

    【讨论】:

    • 如果将in 替换为any 会怎样?
    • 感谢您的编辑,但这不是我想要的。但是谢谢你,我学到了一些新东西:)
    【解决方案3】:

    您正在执行错误的查询。 尝试:

    Video.where.not(id: Video.joins(:categories).where(categories: { id: [20,21,22]}).pluck(:id))
    

    【讨论】:

    • 它会生成多少个查询?我猜只有一个。如果它生成两个查询,则将pluck(:id) 替换为select(:id)
    • 这就是诀窍 :) 我只是有点想有一些更“优雅”的方式来编写这个查询,但我想性能好的时候真的没关系 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多