ruby-on-rails 如何在ActiveRecordError上使用rails-i18 n关联?

svgewumm  于 7个月前  发布在  Ruby
关注(0)|答案(2)|浏览(100)

我正在翻译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}"编写代码?

jjjwad0x

jjjwad0x1#

您可以在en.yml文件中使用它

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

字符串
然后使用以下代码更改救援块

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

0h4hbjxa

0h4hbjxa2#

我以前也遇到过同样的问题。
所以有两种解决方案
a.您可以通过手动指定“代码”来自己刷新翻译的错误

@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.或者你可以使用你正在使用的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,只是想提供一个替代方案以防万一。

相关问题