Reputation: 81
I'm trying to use Mobility in my Rails application with ActiveAdmin as administration panel.
I use Container backend with JSONB column.
I also have activeadmin_json_editor
gem installed so it's not possible to produce bad JSON. Inside my admin resource I permit :translations
attribute using StrongParams.
When editing translations using ActiveAdmin and submitting the form I get the following parameters:
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>
However once the update query gets processed my model has no translations at all:
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>
What am I doing wrong? Should I parse the JSON from the params and use resource.<attribute_name>_backend.write
for each locale?
Upvotes: 1
Views: 815
Reputation: 81
Since I didn't get any answers I dug around and came up with the following solution. In your resource admin model add:
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
This is probably not really the proper way to mass update the translations but I couldn't figure out a better way to do this. Please keep in mind that this doesn't really care if the locale key is valid.
Upvotes: 0