【问题标题】:rails scopes to search in an arrayrails 范围在数组中搜索
【发布时间】:2019-01-22 03:08:34
【问题描述】:

所以我创建了一个面料数据库,其中包含一个列“颜色”数组。例如:紫色和白色条纹面料,colour = ["purple", "white"]

我想创建一个范围,以便用户可以搜索包含某种颜色的面料。

它看起来非常基本,所以我很惊讶我似乎找不到任何解释如何以这种方式使用作用域的东西。

我需要类似下面的代码,它检查颜色数组中的每个项目。谢谢!!

scope :with_colour, -> (colour) { where("colour = ?", colour) }

【问题讨论】:

  • 那么您使用的是 postgres 数组列吗?
  • 是的 postgres!并设法找到了我正在寻找的东西: scope :with_colour, -> (colour) { where(":colour = ANY(colour)", colour: color ) } 现在对我有用 :)

标签: ruby-on-rails scopes


【解决方案1】:

scope :with_colour, -> (colour) { where("color like ?", "%#{colour}%") }

【讨论】:

    【解决方案2】:

    PostgreSQL 有很多有用的 array methods,您可以在 Rails 应用程序中使用它们

    在你的情况下,你也可以这样做:

    scope :scope_name, -> (color) { where("colour @> ?", '{color}')}
    

    【讨论】:

      猜你喜欢
      • 2017-04-09
      • 2020-10-11
      • 1970-01-01
      • 1970-01-01
      • 2014-10-09
      • 2014-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多