gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 06:28:20 26 4
gpt4 key购买 nike

我使用这个 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

最佳答案

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

关于mysql - 按标签名称或资源名称搜索资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29502990/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com