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 :translationsassociation (backed by themuseum_translationstable) for your model. - By using
translations: [:name, :address]in theattributesblock, you tell SearchCop to look for those fields on the joined translation table instead of the mainmuseumstable. - The
optionsblock mirrors this structure to apply the:fulltexttype 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

