ruby-on-rails – 在Rails 3中的区域设置更改后,重定向到相同页面

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 在Rails 3中的区域设置更改后,重定向到相同页面前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。



应用程序使用Rails 3.2.8与以下宝石
gem 'friendly_id','~> 4.0'
gem 'route_translator'

在/config/initializers/i18n.rb中

TLD_LOCALES = {
  "com"  => :en,"jobs" => :en,"net"  => :en,"in"   => :en,"de"   => :de,"ch"   => :de,"at"   => :de,"br"   => :pt,"ar"   => :es,"cl"   => :es,"mx"   => :es 
}

在/app/controllers/application_controller.rb中,使用before-filter来设置每个请求的区域设置:

before_filter :set_auto_locale
def set_auto_locale
  I18n.locale = TLD_LOCALES[request.host.split('.').last]
end

在routes.rb

localized do
  match "label_vacancies/:view_job"=>"job_seekers#view_job"
  get "label_aboutus",:to => "home#about_us",:as => "about_us"
end

用户请求更改语言区域设置时,下面的域应该根据用户请求的语言环境加载.

在初始化器中

domain_based_on_locale = {
    :en => "xxxxx.com",:de => "xxxxx.de",:es => "xxxxx.mx",:pt => "xxxxx.com.br"   
}

在/app/controllers/application_controller.rb中

def set_manual_locale
  if params[:locale] && I18n.available_locales.include?(params[:locale].to_sym)
    cookies['locale'] = { :value => params[:locale],:expires => 1.year.from_now }
    I18n.locale = params[:locale].to_sym
  elsif cookies['locale'] && I18n.available_locales.include?(cookies['locale'].to_sym)
    I18n.locale = cookies['locale'].to_sym
  end
  if domain_based_on_locale[I18n.locale] != request.host
    redirect_to "#{request.protocol}#{domain_based_on_locale[I18n.locale]}#{request.fullpath}",:status => :moved_permanently 
  else
    redirect_to root_path
  end
end

在这种情况下,如下所示的URL中的用户更改语言会出现重定向问题,因为相同的页面根据语言具有不同的URL.

Aboutus:
http://xxxxxxx.com/about-us  # About us route in English
http://xxxxxxx.de/uber-uns      # About us route in German
http://xxxxxxx.mx/quienes-somos # About us route in Spanish

view Job:
http://xxxxxxx.com/jobs/rp-be-company-representante-de-ventas-22042015
http://xxxxxxx.de/ofertas-de-empleo/rp-be-company-representante-de-ventas-22042015

手动语言区域设置更改后,如何重定向到新域中的同一页面.并且可以将运行会话携带到新的域.谢谢你的帮助.

解决方法

你需要翻译request.fullpath的每个段(除了最后一个,看起来像一个资源块).您可以使用Rails’I18n手动执行此操作:
current_path = request.fullpath.split('/')
slug = current_path.pop
locale_path = current_path.map{|part| translate(part)}.join('/')
redirect_to "#{request.protocol}#{domain}#{locale_path}#{slug}"

或者,有处理路由转换的宝石:

> https://github.com/francesc/rails-translate-routes
> https://github.com/enriclluelles/route_translator

就会话而言,不可能在域间共享Cookie.如果您使用本地区域子域(例如,de.xxxxx.com),则可以在share the cookie across all of them.许多站点通过路径进行,例如. xxxxx.com/de/,它完全消除了问题.

支持完全不同的域需要您手动传输会话.你可以通过以下方式来实现:

>生成随机转移令牌xxx123,并将其连接到的会话保存在服务器端
>重定向到new.domain / path?token = xxx123
>使用令牌查找用户的会话并将其设置在浏览器中
>删除令牌以防止重播攻击

仔细考虑转移过程 – 当你做这样的事情时很容易引入安全问题. This SO thread具有使用从其他域加载的图像的方法.

原文链接:https://www.f2er.com/ruby/273503.html

猜你在找的Ruby相关文章