【问题标题】:Before_action ignored rails 4.1.5Before_action 忽略了 rails 4.1.5
【发布时间】:2023-03-14 14:05:01
【问题描述】:

我对 rail 4.1.5 的 before_action 有问题,我的新应用程序似乎完全忽略了它。

我正在尝试在我的应用程序中使用 I18n,我遵循了文档:http://guides.rubyonrails.org/i18n.html

应用控制器:

class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception

  # Set current language to user params[:locale] if exists otherwise, the default_locale is used(en)
  before_action :set_locale

  def set_locale
    I18n.locale = params[:locale] || I18n.default_locale
  end

  def default_url_options(options={})
    logger.debug "default_url_options is passed options: #{options.inspect}\n"
    { locale: I18n.locale }
  end

end

我的“大”控制器:

class WelcomeController < ActionController::Base
  def helloworld
  end
end

我的路线.rb:

Rails.application.routes.draw do
  scope "/:locale" do
    get '/' => 'welcome#helloworld'
  end 
end

en.yml:

en:
  hello: "Hello world !"

fr.yml:

fr:
  hello: "Bonjour le monde !"

我尝试像这样直接在我的控制器中更改 I18n.locale 并且它可以工作...

class WelcomeController < ActionController::Base
  def helloworld
    I18n.locale = :fr
  end
end

这就是为什么我认为我的 before_action 被忽略了,但是为什么?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 internationalization


    【解决方案1】:

    这是因为在这两种情况下您都继承自 ActionController::Base。如果您希望在所有控制器中运行之前的操作,请从您的 ApplicationController 继承所有这些控制器

    class WelcomeController < ApplicationController
      def helloworld
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-23
      • 1970-01-01
      • 1970-01-01
      • 2016-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多