按标记名称或资源名称搜索资源



我使用本教程创建了一个搜索。一切都很顺利。我可以按名称搜索所有资源。

如何按名称或具有该名称的标签搜索资源

例如:

if I search for the word "Tutoring" in my text_field.
I should get all resources that contain the word "Tutoring" in the name, 
And all the resources that have the Tag "Tutoring".

我的当前代码不断出现此错误。

Mysql2::Error: Column 'name' in where clause is ambiguous: 
SELECT COUNT(DISTINCT `resources`.`id`) FROM `resources` 
LEFT OUTER JOIN `resource_mappings` 
ON `resource_mappings`.`resource_id` = `resources`.`id` LEFT OUTER JOIN
`tags` ON `tags`.`id` = `resource_mappings`.`tag_id` WHERE (name like '%Tutoring%') 
AND (tags.name like '%Tutoring%')

型号

class Resource < ActiveRecord::Base
  has_many :resource_mappings, dependent: :destroy
  has_many :tags, through: :resource_mappings
  accepts_nested_attributes_for :tags
end
class ResourceMapping < ActiveRecord::Base
  belongs_to :resource
  belongs_to :tag
end
class Tag < ActiveRecord::Base
  has_many :resource_mappings, dependent: :destroy
  has_many :resources, through: : resource_mappings
end
class Search < ActiveRecord::Base
  def resources
    @resources ||= find_resources
  end
  def find_resources
    resources = Resource.order(:name)
    if name.present?
      ###each work independently, how can I combine these without getting the error above.
      resources = resources.where("name like ?", "%#{name}%")
      resources = resources.includes(:tags).where("tags.name like ?", "%#{name}%")
    end
    resources
  end
end

看起来属性name似乎在您试图访问的多个表中使用。您将希望在name之前添加table_name.,使其看起来像WHERE (table_name.name LIKE...)。只需将table_name替换为您将名称与之进行比较的表和字段:-)

这是我最终使用的代码。

if name.present?    
  resources = resources.includes("tags").where("tags.name like :name OR resources.name like :name", {:name => "%#{name}%" })
end

最新更新