You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Globalize与SearchCop集成报错未知属性,如何实现多语言字段搜索?

Absolutely, you can use Globalize and SearchCop together—you just need to adjust your search_scope to target the translation table fields instead of the main museums table (since Globalize stores localized attributes in a separate museum_translations table, not directly on museums).

Why you're seeing the error

The SearchCop::UnknownAttribute: Unknown attribute museums.name error happens because SearchCop is trying to look for a name column directly on the museums table—but that column doesn't exist. Globalize moves all localized attributes (like name, address) to a joined translation table instead.

Fixed Museum Model Code

Here's how to update your model to make the two gems work in sync:

class Museum < ApplicationRecord
  include SearchCop
  has_one_attached :hero_image
  translates :name, :address, :description, :facilities, :hours, :tickets

  search_scope :search do
    # Reference attributes from the associated translation table
    attributes translations: [:name, :address]
    
    # Apply fulltext options to the translation table fields
    options translations: { 
      name: { type: :fulltext },
      address: { type: :fulltext }
    }
  end
end

How this works

  • Globalize automatically sets up a has_many :translations association (backed by the museum_translations table) for your model.
  • By using translations: [:name, :address] in the attributes block, you tell SearchCop to look for those fields on the joined translation table instead of the main museums table.
  • The options block mirrors this structure to apply the :fulltext type to the correct translation fields.

Bonus: Working with the current locale

Globalize automatically adds a scope to only return translations for the current I18n.locale by default. This means your search will only check localized content for the active language, which is usually what you want. If you need to search across all languages (use this carefully!), you can explicitly remove this scope:

search_scope :search do
  # ... existing attributes/options ...
  unscoped # Removes Globalize's locale filter to search all translations
end

Now when you run Museum.search("art"), SearchCop will query the name and address columns in museum_translations (filtered to your current locale by default) and return matching Museum records.

内容的提问来源于stack exchange,提问作者barnaclebarnes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:53:06