4
votes

I am trying to localize my rails application (webservice). I installed the gem 'rails-i18n', which works fine.

Except that it does not translate ActiveRecord::RecordNotFound message. In rails code: https://github.com/rails/rails/blob/3-2-stable/activerecord/lib/active_record/relation/finder_methods.rb

raise RecordNotFound, "Couldn't find #{@klass.name} with #{conditions.to_a.collect {|p| p.join(' = ')}.join(', ')}"

It seems that the message is hard coded.

Is there any solution, apart not using the Model.find_by_'attribute' ?

3
NOTE: in rails4, find_by_'attribute_name'! is deprecated, so the occurrences of this error is greatly reduce.cyrilchampier

3 Answers

4
votes

Sufficient for my reason to tell user more informative message:

exception.message.match /^Couldn't find (\w+) with (id=([\S]*))?/
msg = t 'activerecord.exceptions.not_found', klass: $1, id: $3

and since I wanted a czech transaltion:

cs:
  activerecord:
    exceptions:
      not_found: "Nelze nalézt %{klass} s id=%{id}"

..when is something hard coded the only way is to hard de-code it

1
votes

You can catch the RecordNotFound exception in the application controller and return a localized message. This way you can also alter the default behavior for 404s:

class ApplicationController < ActionController::Base

  rescue_from ActiveRecord::RecordNotFound, :with => :not_found

  private

    def not_found
      render :json => { :message => I18n.t('exception.record_not_found') },
             :status => :not_found
    end

end
1
votes

Another way in YAML config:

en:
 activerecord:
   exceptions:
     not_found: "%{model_name} not found"

You can also set a plural form for model names, adding as following:

en:
  activerecord:
    models:
      user:
        one: Dude
        other: Dudes