1

我正在尝试在我的 Rails 应用程序中使用 Mobility,并将 ActiveAdmin 作为管理面板。我使用带有 JSONB 列的容器后端。我还activeadmin_json_editor安装了 gem,所以不可能产生错误的 JSON。在我的管理资源中,我允许:translations使用 StrongParams 的属性。

使用 ActiveAdmin 编辑翻译并提交表单时,我得到以下参数:

2.5.3 (#<Admin::QuestionsController:0x00007fd466a9a690>):0 > permitted_params
=> <ActionController::Parameters {"utf8"=>"✓", "_method"=>"patch", "authenticity_token"=>"DwSuN9M9cD27dR7WmitBSMKKgVjhW1om3xwxOJUhK41no8RWH1Xh6L9QNIhOc1NhPYtm5QnKJWh7KEIUvuehUQ==", "commit"=>"Update Question", "id"=>"37", "question"=><ActionController::Parameters {"translations"=>"{\"en\":{\"body\":\"dupa\"}}", "dimension_id"=>"6"} permitted: true>} permitted: true>

但是,一旦更新查询得到处理,我的模型就根本没有翻译:

2.5.3 (#<Admin::QuestionsController:0x00007fd466a9a690>):0 > resource.update(permitted_params["question"])
   (0.4ms)  BEGIN
  ↳ (pry):18
  Dimension Load (0.4ms)  SELECT  "dimensions".* FROM "dimensions" WHERE "dimensions"."id" = $1 LIMIT $2  [["id", 6], ["LIMIT", 1]]
  ↳ (pry):18
   (0.3ms)  COMMIT
  ↳ (pry):18
=> true
2.5.3 (#<Admin::QuestionsController:0x00007fd466a9a690>):0 > resource
=> #<Question:0x00007fd45c284d98
 id: 37,
 body: nil,
 translations: {},
 created_at: Wed, 16 Jan 2019 12:17:38 UTC +00:00,
 updated_at: Fri, 08 Feb 2019 12:07:00 UTC +00:00,
 dimension_id: 6>

我究竟做错了什么?我应该从参数中解析 JSON 并resource.<attribute_name>_backend.write用于每个语言环境吗?

4

1 回答 1

0

由于我没有得到任何答案,因此我四处寻找并提出了以下解决方案。在您的资源管理模型中添加:

  controller do
    def update
      translations = JSON.parse(permitted_params.dig(resource.class.name.downcase, "translations"))
      translations.each do |locale, attributes|
        supported_attributes = attributes.select { |attribute_name, _| resource.class.mobility_attributes.include?(attribute_name) }
        supported_attributes.each do |attribute_name, translation|
          resource.send("#{attribute_name}_backend").send(:write, locale.to_sym, translation.to_s)
        end
      end
      resource.save
      redirect_to admin_questions_path
    end
  end

这可能不是大规模更新翻译的真正正确方法,但我想不出更好的方法来做到这一点。请记住,这并不关心语言环境密钥是否有效。

于 2019-02-12T16:06:55.563 回答