【问题标题】:How do I filter records by locale using gem mobility?如何使用 gem 移动性按区域过滤记录?
【发布时间】:2018-09-26 14:31:52
【问题描述】:

我有一个表mobility_string_translations,但我不明白如何获得它。

现在我有三个记录。两份德文记录和一份西班牙文记录。我只想获取德语记录。

这不起作用:

all_de_posts = Post.i18n.find_by(locale: :de)

【问题讨论】:

  • posts 表有哪些列?
  • 我注意到你用 ruby​​-on-rails-3 标记了这个。您真的将 Mobility 与 RoR3 一起使用吗?它没有针对旧版本进行测试,它测试过的最旧版本是 RoR 4.2。使用这么旧版本的 Rails 可能会遇到一些问题。
  • @ChrisSalzberg 抱歉,搞错了

标签: ruby-on-rails ruby mobility


【解决方案1】:

首先你可能有一个专栏。(让我们说标题。)

在您的模型post.rb 上,您将拥有如下内容:

        class Post < ApplicationRecord
          extend Mobility
          translates :title,  type: :string, locale_accessors: [:en, :de]
        end     

类型对于获取 :de 记录(或 :en)很重要。

schema.rb,您将看到一个表移动性_字符串_translations

  create_table "mobility_string_translations", force: :cascade do |t|
    t.string "locale", null: false
    t.string "key", null: false
    t.string "value"
    t.integer "translatable_id", null: false
    t.string "translatable_type", null: false
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["translatable_id", "translatable_type", "key"], name: "index_mobility_string_translations_on_translatable_attribute"
    t.index ["translatable_id", "translatable_type", "locale", "key"], name: "index_mobility_string_translations_on_keys", unique: true
    t.index ["translatable_type", "key", "value", "locale"], name: "index_mobility_string_translations_on_query_keys"
  end

现在在您的控制台上找到您的记录,使用 locale: :de

irb:> Post.all

irb:> Mobility::ActiveRecord::StringTranslation.where(locale: :de)

正如您在 schema.rb 中看到的 --> “mobility_string_translations”,您可以使用您的列来准确找到您想要的内容。

【讨论】:

  • 太棒了! locale_posts_ids = Mobility::ActiveRecord::StringTranslation .where( locale: I18n.locale, translatable_type: 'Post' ) .pluck(:translatable_id) @posts = Post.where(id: locale_posts_ids)
  • 完美!很高兴我能帮忙:)
  • 我有时会看到这个异常:未初始化的常量 Mobility::ActiveRecord::StringTranslation 嗯...你有想法吗?
  • 需要 'mobility/active_record/string_translation' 帮助
  • 是的,你是对的!我只是在控制台上对其进行了测试。您需要 require 'mobility/active_record/string_translation' 否则您必须先加载 Post.all
猜你喜欢
  • 1970-01-01
  • 2021-04-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-18
  • 2018-03-22
  • 2021-11-20
相关资源
最近更新 更多