【问题标题】:Rails 4.2 Scope queries IS NULL instead of IS NOT NULLRails 4.2 范围查询 IS NULL 而不是 IS NOT NULL
【发布时间】:2018-11-25 03:17:11
【问题描述】:

我刚开始学习 Rails 几天,目前正在使用范围进行查询。

我有这个简化的代码:

Class Product  < ActiveRecord::Base
   belongs_to: producer
   scope: get_items, => {where.not(producer{id: nil})}

启动rails c 并输入Product.get_items 会产生:

SELECT "products".* FROM "products" WHERE (producer_id IS NULL)

当我需要时:

SELECT "products".* FROM "products" WHERE (producer_id IS NOT NULL)

做了一些研究,也尝试了{where("producer_id IS NOT NULL")},但并没有使查询有所不同。

提前致谢!

【问题讨论】:

  • Product.where.not(producer_id: nil) 有用吗?
  • 试试这个scope :get_items, (lambda do where.not(producer_id: nil) end)

标签: ruby-on-rails postgresql ruby-on-rails-4.2


【解决方案1】:

scope: where.not(producer{id: nil} 根本不应该工作。而是:

# if you need to filter by the attribute of the current model
scope :with_producer, -> { where.not(producer_id: nil) }

# if you need to filter by the attribute of the associated model
scope :with_named_producer, -> { joins(:producer).where.not(producers: { name: nil }) }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-27
    • 1970-01-01
    • 1970-01-01
    • 2022-11-21
    • 2013-02-04
    • 1970-01-01
    • 2015-04-21
    相关资源
    最近更新 更多