Mysql2 ::错误:更新到Rails 4.1后

时间:2015-08-05 18:35:06

标签: ruby ruby-on-rails-4.1 mysql2

我最近将我的Rails应用程序从4.0更新到4.1。一切似乎都运行正常,除了我之前正在使用的搜索模型中的这一行。

基本上,我想按标签名称和District_Resource名称搜索/查找District_Resources。

**ex.**
If I search the word "Tutoring" 
*I should get all District_Resources with the Resource_Tag "Tutoring"
*And all District Resources that include the word Tutoring in it's Name. 
(i.e Tutoring Services)

出于某种原因,我不断收到此错误:

(Mysql2::Error: Unknown column 'resource_tags.name' in 'where 
clause': SELECT `district_resources`.* FROM `district_resources`  
WHERE (resource_tags.name like '%Tutoring%' OR district_resources.name like '%Tutoring%')  
ORDER BY `district_resources`.`name` ASC):

但是该列确实存在于Resource_Tags表中。

模型

class DistrictResource < ActiveRecord::Base

  has_many :district_mappings, dependent: :destroy
  has_many :resource_tags, through: :district_mappings

  accepts_nested_attributes_for :resource_tags
end

class ResourceTag < ActiveRecord::Base

  has_many :district_mappings, dependent: :destroy
  has_many :district_resources, through: :district_mappings

end

class Search < ActiveRecord::Base

  def district_resources
    @district_resources ||= find_district_resources
  end

  def find_district_resources
    district_resources = DistrictResource.order(:name)

    district_resources = district_resources.includes(:resource_tags).where("resource_tags.name like :name OR district_resources.name like :name", {:name => "%#{name}%" })

    district_resources
  end

end

SCHEMA

create_table "district_resources", force: true do |t|
  t.string   "name"
  t.string   "description"
  t.string   "website"
  t.string   "phone"
  t.string   "email"
  t.datetime "created_at"
  t.datetime "updated_at"
end

create_table "district_mappings", force: true do |t|
  t.integer  "district_resource_id"
  t.integer  "resource_tag_id"
  t.datetime "created_at"
  t.datetime "updated_at"
end

create_table "resource_tags", force: true do |t|
  t.string   "name"
  t.datetime "created_at"
  t.datetime "updated_at"
end

2 个答案:

答案 0 :(得分:1)

您在where子句中引用了district_resources,但由于您正急切地加载resource_tags,因此未加入查询,因此这里有两个解决方案

1

district_resources = district_resources.joins(:resource_tags).where("resource_tags.name like :name OR district_resources.name like :name", {:name => "%#{name}%" })

2

district_resources = district_resources.includes(:resource_tags).refereces(resource_tags).where("resource_tags.name like :name OR district_resources.name like :name", {:name => "%#{name}%" })

在这两种情况下,我们都告诉我们在where子句中使用resource_tags表,因此将district_resources加入其中

答案 1 :(得分:0)

修正了!!

district_resources = district_resources.includes(:resource_tags).where("resource_tags.name like :name OR district_resources.name like :name", {:name => "%#{name}%" }).references(:resource_tags)

我必须引用Resource_Tags模型