关于 ruby??:ActiveRecord joins throwing Column in where 子句是不明确的错误 – Rails 5.1

ActiveRecord joins throwing Column in where clause is ambiguous error - Rails 5.1

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

我有一个带有 search 动作的 SearchController,其中包含一个收集搜索参数的表单。在表单中,我有一个名称参数的输入和一个类别的选择。搜索成功运行,除非搜索返回 0 个结果,当有结果返回时一切正常。在不应该有结果的情况下,ActiveRecord 会抛出错误:

1
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

有什么可能导致这种情况的想法吗?

项目模型

1
2
3
class Project < ApplicationRecord
  has_and_belongs_to_many :categories
end

类别模型

1
2
3
class Category < ApplicationRecord
  has_and_belongs_to_many :projects
end

搜索控制器

1
2
3
4
5
6
7
8
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

路线

1
2
3
4
5
6
7
Rails.application.routes.draw do
  ...

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

  ...
end

查看

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Search
<%= form_tag(search_path, method: :get) do %>
  <%= label_tag :name %>
  <%= text_field_tag :name, params[:name] %>

  <%= label_tag :category_id %>
  <%= select_tag(:category_id, options_for_select(Category.all.collect {|o| [ o.name, o.id ] }, params[:category_id]), { prompt: 'Select Category'}) %>

  <%= submit_tag"Search" %>
<% end %>

<%= pluralize(@projects.count,"Result") %>
<% @projects.each do |project| %>
  <%= project.name %>
<% end %>


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

1
2
3
4
5
  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

注意 LIKE 查询中的 projects.name