【问题标题】:Search Resources by Tag Name or Resource Name按标签名称或资源名称搜索资源
【发布时间】:2015-06-12 17:20:57
【问题描述】:

我使用此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

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      这是我最终使用的代码。

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

      【讨论】:

        猜你喜欢
        • 2023-04-02
        • 1970-01-01
        • 2012-01-17
        • 2014-04-15
        • 2023-04-03
        • 2014-04-12
        • 1970-01-01
        • 1970-01-01
        • 2019-03-06
        相关资源
        最近更新 更多