ActiveRecord joins throwing Column in where clause is ambiguous error - Rails 5.1
我正在开发一个 Rails 5.1 项目,该项目需要通过记录字段的值以及连接的
我有一个带有
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 %> |
当您连接两个表并且两个表都有一个
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 |
注意