ministryofjustice / govuk_elements_form_builder

Form builder helper methods to develop GOV.UK elements styled applications in Ruby on Rails
https://govuk-elements-rails-guide.herokuapp.com/
MIT License
6 stars 14 forks source link

Locales for attributes in fields_for of a form not working #91

Open lostie opened 7 years ago

lostie commented 7 years ago

I believe the current implementation of the gov form builder bypasses something that the default ActionView::Helpers::FormBuilder does, which is de-structure the field name, so that the locale works both for fields in the base form or fields inside the fields_for section.

Gov Form Builder behaviour for locales:

# /govuk_elements_form_builder-72d4f260de41/lib/govuk_elements_form_builder/form_builder.rb @ line 253 GovukElementsFormBuilder::FormBuilder.localized:
                                                                                                                                                                                                                252: def self.localized scope, attribute, default, object_name
    => 253:   key = "#{object_name}.#{attribute}"
    254:   translate key, default, scope                                                                                                                                                                        255: end

[28] pry(GovukElementsFormBuilder::FormBuilder)> "#{object_name}.#{attribute}"
=> "detainees[offences_attributes][0].name"

Rails behaviour for locales:

# actionview-5.0.0.1/lib/action_view/helpers/tags/translator.rb @ line 7 ActionView::Helpers::Tags::Translator#initialize:

     5: def initialize(object, object_name, method_and_value, scope:)
THIS => 6:   @object_name = object_name.gsub(/\[(.*)_attributes\]\[\d+\]/, '.\1') 
^^^^ THIS BEHAVIOUR IS MISSING IN THE GOV FORM BUILDER
     7:   @method_and_value = method_and_value
     8:   @scope = scope
     9:   @model = object.respond_to?(:to_model) ? object.to_model : nil
    10: end

# actionview-5.0.0.1/lib/action_view/helpers/tags/translator.rb @ line 13 ActionView::Helpers::Tags::Translator#translate:

    12: def translate
 => 13:   translated_attribute = I18n.t("#{object_name}.#{method_and_value}", default: i18n_default, scope: scope).presence
    14:   translated_attribute || human_attribute_name
    15: end

[4] pry(#<ActionView::Helpers::Tags::Translator>)> object_name
=> "detainees.offences"
[5] pry(#<ActionView::Helpers::Tags::Translator>)> method_and_value
=> "name"