【问题标题】:How to make this Active record query work如何使这个活动记录查询工作
【发布时间】:2012-06-30 15:57:00
【问题描述】:

在我的数据库中,我有一堆不同城市名称的列表。我试图只保留此数据库中城市名称 = X 的列表并删除所有其他城市。

我正在尝试以下活动记录查询:

@unwanted_cities = Listing.where('city not in (?)', Listing.where('city = ?', "X"));

但我得到了这个错误

ActiveRecord::StatementInvalid in Unwanted_cities#index

Showing /Users/AM/Documents/RailsWS/app0521/app/views/unwanted_cities/index.html.erb where     line #31 raised:

PG::Error: ERROR:  operator does not exist: character varying <> integer
LINE 1: SELECT "listings".* FROM "listings"  WHERE (city not in (4,1...
                                                     ^
HINT:  No operator matches the given name and argument type(s). You might need to add  explicit type casts.
: SELECT "listings".* FROM "listings"  WHERE (city not in         (4,10,13,17,18,19,21,23,26,28,29,31,36,39,46,48,49,52,90,97,101,103,105,108,109,111,115,94,5      ,219..............))

我做错了什么?

【问题讨论】:

    标签: ruby-on-rails postgresql activerecord


    【解决方案1】:

    @unwanted_cities = Listing.where('city != ?', "X")

    如果我阅读的内容是正确的,那么您希望城市没有名称“X”。您将通过执行上述代码行获得这些城市。

    如果你想“移除”所有这些城市,

    @unwanted_cities.delete_all

    @unwanted_cities.destroy_all

    【讨论】:

    • 是的,我想删除城市不是 X 的条目。谢谢,我会试试这个查询。根据我对 SQL 的了解,我认为不等于的符号是 。我用这个符号尝试了查询,但没有用。我现在就试试你的方法。
    • @banditKing 两者都应该工作。 Listing.where('city &lt;&gt; ?', "X")
    • 非常感谢。你的建议奏效了。出于好奇,我将再次尝试 :)
    猜你喜欢
    • 2013-12-30
    • 2021-10-30
    • 1970-01-01
    • 2012-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-06
    • 2013-10-15
    相关资源
    最近更新 更多