繁体   English   中英

兰萨克搜索和翻译

[英]Ransack search and translations

我正在尝试在与翻译表有关联的模型上使用ransack。

翻译由global gem管理。

问题是,当我尝试在:name列的模型表中使用ransack进行搜索时,它没有显示任何内容,因为:name信息存储在另一个表中。

有什么线索可以在关联翻译表中进行搜索搜索吗? 我知道有可能使用洗劫案,但我不知道要在其中放入哪个代码。

虽然@rlarcombe的答案在这种特定情况下有效,但您会放掉ransack提供的所有谓词(例如eq,cont等),基本上是自己编写搜索查询。

Globalize将转换表添加为关联表,而ransack提供了通过在可搜索属性前面加上关联表名来搜索关联表的功能。

对于您的情况,这将起作用,并且仍然允许您使用ransack的所有谓词。

User.with_translations(I18n.locale).ransack(translations_name_eq: 'John')

您只需替换谓词后缀,即可将其他谓词(例如cont (包含))用于ILIKE匹配:

User.with_translations(I18n.locale).ransack(translations_name_cont: 'John')

全球化为您提供了一种with_translations的类方法,例如:

User.with_translations('en')

因此,您可以在模型上设置自己的范围,以利用以下优势:

def self.with_translated_name(name_string)
  with_translations(I18n.locale).where('user_translations.name' => name_string)
end

然后,您可以在相关模型的ransackable_scopes数组中公开此范围 ,例如:

private

def self.ransackable_scopes   
  %i(with_translated_name) 
end

有了它,您应该能够执行以下操作:

User.ransack({ with_translated_name: "John" }) 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM