>我对与搜索的关联有问题
class Manufacturer < ApplicationRecord
has_many :translations, class_name: 'ManufacturerTranslation', dependent: :destroy
def self.search(query)
q = query.to_s.parameterize.gsub('-',' ').split
joins(:translations).where("lower(name) LIKE ?", "%#{q}%")
end
and
class ManufacturerTranslation < ApplicationRecord
belongs_to :manufacturer
end
因此,当我尝试对其进行搜索并调用翻译时
Manufacturer.search('fra').last.translations
它只给了我名称包含fra
的翻译,而不是所有的翻译
所以我总共为这个制造商提供了 6 个翻译
但是搜索后只得到2
数据库架构
create_table "manufacturer_translations" do |t|
t.integer "manufacturer_id"
t.string "locale"
t.string "name"
t.string "image_source_url"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["manufacturer_id"], name: "index_manufacturer_translations_on_manufacturer_id"
t.index ["name"], name: "index_manufacturer_translations_on_name"
end
create_table "manufacturers", do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.boolean "deleted", default: false
end
在拆分字符串时,您必须遍历所有实体才能搜索它们。而且您还必须将结果缩小。尝试以下代码:
def self.search(query)
q = query.to_s.parameterize.gsub('-',' ').split
conditions = ''
q.each do |qu|
conditions = "#{conditions} OR " if conditions.present?
conditions = "#{condidtions} lower(manufacturers.name) LIKE %#{qu.downcase}%"
end
joins(:translations).where(conditions)
end
假设你遵循 Rails 约定,我建议你替换它
joins(:translations).where("lower(name) LIKE ?", "%#{q}%")
跟
joins(:translations).where("lower(manufacturers.name) LIKE ?", "%#{q}%")
可能需要玩弄引号