我在试着翻译https://github.com/lifo/docrails/blob/master/activerecord/lib/active_record/associations.rb
在我的控制器文件中,我有:
@book = Book.find(params[:id])
begin
@book.destroy
rescue ActiveRecord::DeleteRestrictionError => e
flash[:error]= e.message # <<< Translate this message ?
end这是我使用的转换文件:https://github.com/svenfuchs/rails-i18n/blob/master/rails/locale/th.rb
如何为translate "#{e.message}"编写代码
发布于 2011-12-05 15:45:13
您可以在en.yml文件中使用它
activerecord:
book:
error: 'book error: %{e}'你可以用这个改变你的救援区
flash[:error] = t("book.error") % {:e => e.message}这在ma案例中是有效的。
发布于 2020-03-20 13:42:04
我以前也遇到过同样的问题。
所以有两种解决方案;
a.您可以通过手动指定"code“来刷新翻译后的错误。
@book = Book.find(params[:id])
begin
@book.destroy
rescue ActiveRecord::DeleteRestrictionError => e
flash[:error]= I18n.t('en.activerecord.errors.messages.restrict_dependent_destroy')
endb.或者你可以使用你正在使用的gem rails-i18n;
首先,您需要配置book模型:
has_many :children, dependent: :restrict_with_error然后你就可以这样做
@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我假设您使用的是:restrict_with_exception而不是:restrict_with_error,只是为了以防万一提供一个替代方案。
https://stackoverflow.com/questions/8326442
复制相似问题