ruby-on-railsglobalize3

Limit globalize_accessor locales to arguments from controller/view


I'm using the globalize_accessor gem to render a form that has multilingual inputs for a :name field, and would like to limit the languages a user can input based on which Languages have been passed as arguments to the globalize_attribute_names method. Is something like this possible?

Here's what I have so far:

chart.rb

class Chart < ActiveRecord::Base
  belongs_to :chart_type
  belongs_to :section
  has_many :data_points, dependent: :destroy

  translates :name
  globalize_accessors :attributes => [:name]

  validates :name, presence: true

  accepts_nested_attributes_for :data_points
end


charts/new.html.haml

= simple_form_for chart,  html: {multipart: true} do |f|
  - Chart.globalize_attribute_names.each do |lang|
    = f.input lang
  = f.input :chart_type, collection: @chart_types
  = f.input :section, collection: @sections, label_method: :heading
  = f.simple_fields_for :data_points, chart.data_points.build do |c|
    = c.input :file, as: :file
  = f.submit

UPDATE

To my knowledge, the only way to define locales for translation is to pass them in explicitly at the model level. When trying to use a method to define these however, I see an undefined local variable or method error. The method I'm using currently is for experimentation, and an ideal use case would have this method call the Chart's parent and return the acceptable languages for it. Here's the updated code:

class Chart < ActiveRecord::Base
  belongs_to :chart_type
  belongs_to :section
  has_many :data_points, dependent: :destroy

  translates :name
  globalize_accessors :attributes => [:name], locales: languages

  validates :name, presence: true

  accepts_nested_attributes_for :data_points

  def self.languages
    [:en, :fr]
  end

Solution

  • You're seeing an undefined local variable or method error because you are defining the method languages after you use it in the class. Just define the method above the globalize_accessors call and you should be fine:

    class Chart < ActiveRecord::Base
    
      ...
    
      def self.languages # <= define this first
        [:en, :fr]
      end
    
      globalize_accessors :attributes => [:name], locales: languages