【问题标题】:Why is Rails update action redirecting to default_locale only?为什么 Rails 更新操作仅重定向到 default_locale?
【发布时间】:2013-12-24 12:25:11
【问题描述】:

在我的多语言 Rails 应用程序中,我有一个 ProfilesController。我正在使用 GET 变量 section 将视图拆分为不同的选项卡。我还将该变量存储在 session 中,以便在请求中记住它。

class ProfilesController < ApplicationController

  before_action :signed_in_user
  before_action :find_profile
  before_action :set_section, :only => [:show, :edit]

  def show
  end

  def edit
  end

  def update
    if @profile.update_attributes(profile_params)
      flash[:success] = t('profiles.flash_messages.profile_updated')
      redirect_to edit_profile_path(:section => session[:section])
    else
      @title = t("views.#{session[:section]}")
      render :edit
    end
  end

private

def find_profile
  @profile = current_user.profile
end

def set_section
  section = Profile::SECTIONS.include?(params[:section]) ? params[:section] : Profile::SECTIONS[0]
  session[:section] = section
end

我不明白为什么我的update 操作会不断重定向到default_locale,而不是用户选择并因此存储在会话中的语言环境。

谁能告诉我这里缺少什么?

这是我的routes.rb 文件的摘录:(请注意,我在这里使用单数资源,因为每个用户只能拥有一个个人资料)

MyApp::Application.routes.draw do

  scope '(:locale)' do

    resource  :membership

    ...

    get 'change_locale', :to => 'locales#change_locale'

  end

end

更新:

class ApplicationController < ActionController::Base

  before_action :set_locale

  protected

  def set_locale
    if params[:locale]
      if I18n.available_locales.include?(params[:locale].to_sym)
        I18n.locale = session[:locale] || params[:locale] || I18n.default_locale
      end
    end
  end

  def default_url_options
    { :locale => I18n.locale }
  end

end

【问题讨论】:

  • 你能显示区域设置的位置吗?
  • @SergeyKutsko:刚刚更新了我的问题。
  • 已更新。别忘了我)
  • 您在哪里设置和更改会话[:locale]?更新帖子。

标签: ruby-on-rails ruby ruby-on-rails-3 internationalization rails-i18n


【解决方案1】:

尝试使用:

redirect_to edit_profile_path(:section => session[:section], :locale => I18n.locale)

class ApplicationController < ActionController::Base
  before_action :set_locale

  def default_url_options(options={})
    { locale: I18n.locale }
  end

protected
  def set_locale
    I18n.locale = (session[:locale] || params[:locale]).to_s.downcase.presence || I18n.default_locale
  end
end

这会有所帮助。

【讨论】:

  • 谢谢,但不幸的是,这也没有用。
  • 感谢您再次更改代码,但仍然无法正常工作:-(
  • 是的,做到了! set_locale 函数是关键。我什至不需要在edit_profile_path 中传递locale。它甚至可以在没有它的情况下工作!非常感谢您的帮助!!
【解决方案2】:

我想你忘了设置default_url_options

# app/controllers/application_controller.rb
def default_url_options(options={})
  { :locale => ((I18n.locale == I18n.default_locale) ? nil : I18n.locale) }
end

【讨论】:

  • 谢谢,但我想我已经有了。我在上面发布了我的 ApplicationController 以更新我的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-02
  • 2017-07-03
  • 1970-01-01
  • 2011-04-25
  • 1970-01-01
  • 2011-12-27
相关资源
最近更新 更多