Rails 5自定义查询与多个关键字

Stu*_*ter 0 ruby-on-rails ruby-on-rails-5

我有一个producttag模型has_and_belongs_to_many通过连接表有关联products_tags.我有许多带有Limestones标签的产品,许多带有Moldings标签的产品,但我想只展示那些兼容两者的产品.我知道我遗漏了一些Rails/Ruby的基础知识,但我仍然很难看到它.

我正在尝试下面的代码给我错误 PG::UndefinedTable: ERROR: missing FROM-clause entry for table "tag"

products_controller.rb

...
def index
      if params[:query]
        @products = Product.search_for(params[:query]).includes(:tags)
        @mouldings = @products.where('tag.name LIKE ? AND tag.name LIKE ?', 'Mouldings', 'Limestones')
      else
        ...
      end
end
...
Run Code Online (Sandbox Code Playgroud)

foo*_*dev 5

尝试以下tags代替tag

@mouldings = @products.where('tags.name ILIKE ? AND tags.name ILIKE ?', 'Mouldings', 'Limestones')
Run Code Online (Sandbox Code Playgroud)

因为你的表名tags不是tag,它清楚地表明

PG :: UndefinedTable:错误:缺少表"tag"的FROM子句条目

更新

@products = Product.search_for(params[:query]).where('true')
@mouldings = @products.includes(:tags).where('tags.name ILIKE ? AND tags.name ILIKE ?', '%Mouldings%', '%Limestones%')
Run Code Online (Sandbox Code Playgroud)

更新2

@mouldings = @products.includes(:tags).where('tags.name ILIKE ?', '%Mouldings%')
@limestones = @mouldings.where('tags.name ILIKE ?', '%Limestones%')
Run Code Online (Sandbox Code Playgroud)