Rails 设置了默认语言以后,如何去掉后面的参数

nicetyler · August 17, 2018 · Last by nicetyler replied at August 17, 2018 · 1496 hits

我这里使用的是 rails 4.1.6 config/application.rb 的代码如下:

class Application < Rails::Application
    # Settings in config/environments/* take precedence over those specified here.
    # Application configuration should go into files in config/initializers
    # -- all .rb files in that directory are automatically loaded.

    # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
    # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
    # config.time_zone = 'Central Time (US & Canada)'

    # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
    config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
    config.i18n.default_locale = :zh_CN
    config.i18n.available_locales = [:zh_CN,:en]
  end

application_controller 的代码如下:

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception

  before_action :public_variables

  before_action :set_locale
  def set_locale
    I18n.locale = params[:locale] || I18n.default_locale
  end
  def default_url_options
    {locale: I18n.locale}
  end

  def public_variables
    head_device = Solution.new
    head_device.free_result
    @device_list = head_device.solution_index(3,0)
  end

end

路由文件 route.rb:

scope '(:locale)' do
root 'static_pages#home'

    post 'photos' => 'photos#upload'

    resources :presses
end

我的问题就是我这里每次点链接比如说 root_path,他这里显示的就是是这样的路径http://localhost:3000/zh_CN。 怎么样可以把这个 zh_CN 去掉啊,不然一个页面对应好几个 url。

去掉这个就行:

def default_url_options
  {locale: I18n.locale}
end
Reply to pinewong

太感谢了!!!已经弄好了👍 👍 👍

nicetyler closed this topic. 18 Aug 21:25
nicetyler reopened this topic. 20 Aug 09:40
You need to Sign in before reply, if you don't have an account, please Sign up first.