ActiveRecord加入了在where子句中出现模糊错误的抛出列--Rails 5.1

时间:2018-05-01 04:31:11

标签: ruby-on-rails ruby join activerecord

我正在开发一个Rails 5.1项目,该项目需要按记录字段的值索引和搜索Project记录,以及存在连接的Category记录({{1} }拥有并属于许多Project)。

我有Category行为SearchController,其中包含收集搜索参数的表单。在表单中,我有一个名称参数的输入和一个类别的选择。搜索成功运行,除非搜索返回0结果,当有结果返回时,一切正常。如果没有结果,ActiveRecord会抛出错误:

search

关于可能导致这种情况的任何想法?

项目模型

Mysql2::Error: Column 'name' in where clause is ambiguous: SELECT COUNT(*) FROM `projects` INNER JOIN `categories_projects` ON `categories_projects`.`project_id` = `projects`.`id` INNER JOIN `categories` ON `categories`.`id` = `categories_projects`.`category_id` WHERE (name LIKE '%something%') AND `categories`.`id` = 1

类别模型

class Project < ApplicationRecord
  has_and_belongs_to_many :categories
end

SearchController

class Category < ApplicationRecord
  has_and_belongs_to_many :projects
end

路线

class SearchController < ApplicationController
  def search
    projects = Project.all
    projects = projects.where('name LIKE ?', "%#{params[:name]}%") if params[:name].present?
    projects = projects.joins(:categories).where(categories: { id: params[:category_id] }) if params[:category_id].present?
    @projects = projects
  end
end

查看

Rails.application.routes.draw do
  ...

  get "search", to: "search#search"

  ...
end

1 个答案:

答案 0 :(得分:2)

当您连接两个表并且两个表都有name列时,您必须告诉数据库您要匹配哪个name列。

  def search
    @projects = Project.all
    @projects = @projects.where('projects.name LIKE ?', "%#{params[:name]}%") if params[:name].present?
    @projects = @projects.joins(:categories).where(categories: { id: params[:category_id] }) if params[:category_id].present?
  end

请注意projects.name查询中的LIKE