Last Updated: February 25, 2016
·
2.281K
· mpatrick

Delocalize (or localize) attributes on Rails with I18n::Alchemy

You need to "convert" your parameters when handling localized fields like monetary and distance fields? Don't worry, I have a simple tip for you.

Thanks @carlosantoniodasilva !!

You can use this for numbers (float...decimal...) and date.

First, you need to use a gem called 'i18n_alchemy', so add this to your gemfile:

If you're using rails 3.x, put this line:

gem 'i18n_alchemy'

If you're using rails4, put this line:

gem 'i18n_alchemy', github: 'mpatrick/i18n_alchemy', branch: 'rails4'

Now, you have to include this on your model that you have attributes to localize.

class TributaryParam < ActiveRecord::Base
  include I18n::Alchemy
  localize :value, using: :number
  localize :date, using: :date
end

So, now you can see on CREATE and UPDATE that you receive parameters and "delocalize" it, and in your EDIT you receive this localized on your view.

If you're using Rails 3.x, do this

class TributaryParamController < InheritedResources::Base
  def create
    x = TributaryParam.new
    x.localized.assign_attributes(params[:tributary_param])
    x.save!
  end

  def update
    resource.localized.update_attributes(params[:tributary_param])
    redirect_to your_path
  end

  def edit
    @localized = resource.localized
  end
end

If you're using Rails 4.x, do this

class TributaryParamController < InheritedResources::Base
  def create
    x = TributaryParam.new
    x.localized.assign_attributes(permitted_params[:tributary_param])
    x.save!
  end

  def update
    resource.localized.update_attributes(permitted_params[:tributary_param])
    redirect_to your_path
  end

  def edit
    @localized = resource.localized
  end

  private

  def permitted_params
    params.permit(tributary_param: [:value])
  end
end

NOTE_1:

I'm using inherited_resources, so if you don't, the method RESOURCE won't work and you'll to substitute it for Object.find(:id) and attribute this to a instance variable.

NOTE_2:

In rails 4.x the model methods like attraccessible are removed, and because this you need to use permittedparams, read THIS about strong_parameters.