5
votes

I'm trying to translate https://github.com/lifo/docrails/blob/master/activerecord/lib/active_record/associations.rb

In my controller file I have:

@book = Book.find(params[:id])

begin
  @book.destroy
rescue ActiveRecord::DeleteRestrictionError => e
  flash[:error]= e.message # <<< Translate this message ?
end

This is the translation file I use : https://github.com/svenfuchs/rails-i18n/blob/master/rails/locale/th.rb

How do I write code for translate "#{e.message}"?

2

2 Answers

1
votes

You can use this in your en.yml file

activerecord:
   book:
    error: 'book error: %{e}'

and u can chane ur rescue block with this

flash[:error] = t("book.error") % {:e => e.message}

this works in ma case

0
votes

I was facing the same issue once before.

So there are two solutions;


a. Either you can flash the translated error yourself by manually specify the "code"

@book = Book.find(params[:id])

begin
  @book.destroy
rescue ActiveRecord::DeleteRestrictionError => e
  flash[:error]= I18n.t('en.activerecord.errors.messages.restrict_dependent_destroy')
end

b. Or you can use the gem rails-i18n which you are using anyway;

Fristly you need to config your book model:

has_many :children, dependent: :restrict_with_error

then you can just do

@book = Book.find(params[:id])

if @book.destroy
  # show success message
else
  flash[:error] = resource.errors.messages[:base].join(', ')
  # should include the translated error message if you are using rails-i18n
end

I assume you are using :restrict_with_exception instead of :restrict_with_error, just want to provide an alternative just in case.