globalize / globalize-accessors

Easily access (read and write) globalize translated fields without fiddling with locale
Other
110 stars 43 forks source link

Correct way to create form that accepts multiple locales #5

Closed jboler closed 10 years ago

jboler commented 10 years ago

Am I correct in thinking this gem is helping accomplish something like the code below that currently works for me? If so is this my of creating a form for different locales deprecated?

In model

accepts_nested_attributes_for :translations

In a haml form view:

  - [:en, :es, :fr].each do |lan|
    = f.globalize_fields_for lan do |j|
      = j.text_field :name

In lib:

module ActionView
  module Helpers
    class FormBuilder
      def globalize_fields_for(locale, *args, &proc)
        raise ArgumentError, "Missing block" unless block_given?

        @index = @index ? @index + 1 : 1

        object_name = "#{@object_name}[translations_attributes][#{@index}]"
        object = @object.translations.find_by_locale locale.to_s

        @template.concat @template.hidden_field_tag("#{object_name}[id]", object ? object.id : "")
        @template.concat @template.hidden_field_tag("#{object_name}[locale]", locale)

        if @template.respond_to? :simple_fields_for
          @template.simple_fields_for(object_name, object, *args, &proc)
        else
          @template.fields_for(object_name, object, *args, &proc)
        end
      end
    end
  end
end
tomash commented 10 years ago

Your solution is not "deprecated", it's just that this gem provides nice and short api for the field names and predefined locales.

shioyama commented 10 years ago

Actually I was thinking of creating a simple gem to make it easy to create forms, but that's really separate from this gem. I'm closing this, if I ever get around to it I'll mention it here.