【问题标题】:How to setup a search query如何设置搜索查询
【发布时间】:2019-09-29 22:11:57
【问题描述】:

我正在构建一个 Rails 5 应用程序,在这个应用程序中,我让我的用户为他们正在寻找的公寓添加搜索配置文件。

他们可以将以下内容添加到他们的用户对象中:

  • min_size
  • 最大尺寸
  • 最低价格
  • 最高价格
  • 房间

例如,用户可能正在寻找最小 (min_size) 100 ft2 和最大 (max_size) 200 ft2 的公寓。他们只想每月支付最低 (min_price) 500 美元,最高 (max_price) 每月 1200 美元,并且公寓应该有至少 3 个房间。

我会定期从远程数据库中获取有关公寓的信息,并且每次我想检查是否有任何搜索配置文件与公寓数据匹配。

我如何创建一个 SQL where 查询来检查这个?

这就是我在 User 对象上尝试的类方法。

def self.match(size, price, rooms)
  User.where("size_min >= ? AND size_max <= ? AND price_min >= ? AND price_max <= ? AND rooms == ?", size, size, price, price, rooms)
end

然后运行的查询是

User Load (0.2ms)  SELECT  "users".* FROM "users" WHERE (size_min >= 100 AND size_max <= 100 AND price_min >= 600 AND price_max <= 600 AND rooms == 3) LIMIT ?  [["LIMIT", 11]]

但这看起来不太好。我在下面有一个我想要匹配的示例用户对象。

<User id: 12, provider: "email", allow_password_change: false, firstname: "John", lastname: "Doe", email: "example@gmail.com", phone: "32323", area: "San Antonio", rooms: 3, size_min: 100, size_max: 200, price_min: 500, price_max: 1200, is_admin: true, created_at: "2019-09-26 15:43:15", updated_at: "2019-09-26 22:06:34"> 

公寓的对象信息不是范围而是绝对数据:

[{"rooms":"3","size":"80","price":"7315"}]

【问题讨论】:

  • == 应该是 =。尝试更改它是否有效。
  • 没有变化,但也许我不应该在查询中使用 AND,它应该是 OR 还是别的什么?
  • 最后一段代码是你用来执行查询的数据?
  • 是的,这是正确的,但这只是一个例子。但是数据和表格总是一样的。
  • 你怎么知道最大和最小尺寸和价格是多少?

标签: ruby-on-rails


【解决方案1】:

您正在编写的查询似乎有不正确的不等式检查,请尝试以下一个,

def self.match(size, price, rooms)
  User.where("(? BETWEEN size_min AND size_max) AND (? BETWEEN price_min AND price_max) AND rooms = ?", size, price, rooms)
end

参考:https://dev.mysql.com/doc/refman/8.0/en/comparison-operators.html#operator_between

【讨论】:

    猜你喜欢
    • 2014-05-09
    • 1970-01-01
    • 1970-01-01
    • 2021-05-08
    • 1970-01-01
    • 1970-01-01
    • 2014-05-13
    • 2022-01-16
    • 1970-01-01
    相关资源
    最近更新 更多