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

时间:2015-04-07 23:09:34

标签: mysql ruby search ruby-on-rails-4 tags

我使用此tutorial创建了一个搜索。一切都很好。我可以按名称搜索所有资源。

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

例如:

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

2 个答案:

答案 0 :(得分:1)

看起来好像在您尝试访问的多个表中使用了属性name。您需要在table_name.之前添加name,因此它看起来像WHERE (table_name.name LIKE...)。只需将table_name替换为您要将名称与之比较的表和字段: - )

答案 1 :(得分:1)

这是我最终使用的代码。

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