Rails I18n在verification.rb中的验证方法不起作用? [英] Rails I18n in verification.rb verify method does not work?

查看:129
本文介绍了Rails I18n在verification.rb中的验证方法不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用I18n国际化插件,但没有翻译1条信息:

I am using I18n internationnalization plugin, but it's not translating 1 piece of information :

在我的一个控制器中,我有一个类似的验证方法:

In one of my controller, I have a verify method like this :

  # Verify user is authenticated
  verify :only => [ :destroy, :create, :update, :new, :comment ],
     :session => :user_id,
     :add_flash => { :error => I18n.t(:'Exceptions.not_logged_in') },
     :redirect_to => { :controller => 'main' , :action => 'index' }

但是,使用I18n.t(:'Exceptions.not_logged_in')始终显示default_locale,在这种情况下为英语.

However, using I18n.t(:'Exceptions.not_logged_in') always display the default_locale, in this case, english.

我的Application_Controller中有一个设置语言环境的before_filter.

I have in my Application_Controller a before_filter that sets the locale.

有人可以帮助我理解并帮助我找到解决方法吗?

Can anybody help me understand, and help me find a workaround?

谢谢!

P.S .:我尝试在此验证方法之前添加对set_locale的调用,但未成功(在我的控制器中)

P.S.: I tried adding a call to set_locale before this verification method without success (in my controller)

推荐答案

由于verify是在类定义级别调用的类方法,因此在加载控制器时会评估其参数(包括I18n.t调用).为了使I18n.t正常工作,每次执行相关的控制器动作时都需要对其进行评估. verify无法执行此操作.

Since verify is a class method called at the class definition level, its arguments, including the I18n.t call, are evaluated as the controller is loaded. In order for I18n.t to work properly, it needs to be evaluated each time the relevant controller actions are executed. verify does not have the ability to do this.

相反,我建议您使用前置过滤器:

Instead, I suggest you use a before filter:

before_filter :verify_session, :only => [:destroy, :create, :update, :new, :comment]

def verify_session
  unless session[:user_id]
    flash[:error] = I18n.t('Exceptions.not_logged_in')
    redirect_to :controller => 'main', :action => 'index'
  end
end

此外,请注意,在过滤器继续工作之前,已不推荐使用verify并将其移至Rails 3中的插件.

Also, note that verify has been deprecated and moved to a plugin in Rails 3, while before filters continue to work.

这篇关于Rails I18n在verification.rb中的验证方法不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆