【问题标题】:Search with MongoDB in rails 4在 Rails 4 中使用 MongoDB 进行搜索
【发布时间】:2014-03-27 09:52:01
【问题描述】:

它会按原样搜索完整的单词,我想显示所有从它开始的单词的结果。就像在输入 pro 之后一样,它应该显示所有以 pro 开头的单词,例如 product1、product2 等。

这是我的产品控制器的索引操作 定义索引

if params[:search]
    @products = Product.search(params[:search]).order("created_at ASC")
  else
    flash[:alert]= "No matches Found."
    @products = Product.all
  end

结束

型号

 class Product
 include Mongoid::Document

 embeds_many :brands
 field :name, type: String
 field :description, type: String
 field :price, type: Float


def self.search(query)
  any_of({name: query})
end
end

请帮我定义一个合适的搜索。

【问题讨论】:

    标签: ruby-on-rails mongodb


    【解决方案1】:

    您可以使用 RegEx 搜索此内容。作为,

    Product.any_of(name: /^pro/) #all products starting with "pro"
    Product.any_of(name: /pro$/) #all products ending with "pro"
    Porduct.any_of(name: /pro/) #all products having "pro" anywhere in name
    

    【讨论】:

    • 但是当我写 any_of({name: /^query/}) 时,它不会找到任何产品
    • 在您的情况下,查询只是一个变量。所以需要通过Product.any_of(name: /^#{query}/)这样的方式查询才能得到想要的结果。
    • 那行得通...谢谢...但是当我搜索一个不存在的单词时,它会显示flash msg“未找到匹配项”,但不会显示所有产品。为什么会这样?
    • 因为您在查询中要求返回与您输入的查询匹配的产品/文档。万一,如果没有匹配,你想显示所有结果,那么你必须做类似products= Product.any_of(name: /^#{query}/); products = Product.all unless products.any? 但这似乎不是任何事情的有效解决方案......可能是你的要求是不同的。如果您有任何疑问,请告诉我。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-13
    • 1970-01-01
    • 2014-07-07
    • 2014-11-19
    • 2018-01-10
    相关资源
    最近更新 更多