Last active
August 29, 2015 14:15
-
-
Save Arakaki-Yuji/dee4e9e055218deeaec3 to your computer and use it in GitHub Desktop.
ActiveRecord::RecordNotFoundのエラーメッセージを翻訳する ref: http://qiita.com/arakaji/items/7a7c262f35b17195d3d7
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class UserController < ApplicationController | |
def show | |
begin | |
@user = User.find(9999) | |
rescue ActiveRecord::RecordNotFound => e | |
# 翻訳処理を書く。 | |
end | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def translate_record_not_found(error_msg) | |
match = error_msg.match(/^Couldn't find ([\S].*) with '([\S]*)'=([\S].*)$/) | |
# モデル名を翻訳する | |
t_model = I18n.t('activerecord.models.' + match[1].underscore) | |
# 属性名を翻訳する | |
t_attr = I18n.t('activerecord.attributes.' + match[1].underscore + '.' + match[2]) | |
I18n.t('errors.messages.not_found', | |
{ klass: t_model, attribute: t_attr, value: match[3] }) | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
ja: | |
activerecord: | |
models: | |
user: ユーザー | |
attributes: | |
user: | |
id: "ID" | |
errors: | |
messages: | |
not_found: "%{klass}の%{attribute}=`%{value}`は見つかりません" | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class UserController < ApplicationController | |
def show | |
begin | |
@user = User.find(9999) | |
rescue ActiveRecord::RecordNotFound => e | |
raise ActiveRecord::RecordNotFound, translate_record_not_found(error_msg) | |
end | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
ja: | |
activerecord: | |
models: | |
user: ユーザー | |
attributes: | |
user: | |
id: "ID" | |
errors: | |
messages: | |
not_found: "%{klass}の%{attribute}=`%{value}`は見つかりません" | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment