Rails 4 before_action有时候效果不好

时间:2014-11-01 05:02:32

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

我的环境

  • ruby​​ 2.1.4(发生在2.1.2中)
  • Rails 4.1.6(发生在4.1.1中)开发Env

我在before_action中设置了@current_store。

class Store::ApplicationController < ApplicationController
  before_action :set_current_store

  private
  def set_current_store
    Rails.logger.debug "set_current_store is called"
    @current_store = Store.find session[:id]
  end
end

class Store::FooController < Store::ApplicationController
  def index
    @foos = Foo.where(store_id: @current_store.id)
  end
end

然后我访问http://my.domain/store/foos

有时运行良好并获得200响应,我可以在development.log中找到“set_current_store被调用”,但有时我得到500,我在development.log中找不到“set_current_store”。

然后我重新加载并得到同样的错误。但是我在vim中打开store / application_controller.rb并只保存(:w)而不更改代码。并重新加载我总能获得200响应。

为什么有时会忽略before_action?

我的config / environments / development.rb

Rails.application.configure do
  config.cache_classes = false
  config.eager_load = false
  config.consider_all_requests_local       = true
  config.action_controller.perform_caching = false
  config.action_mailer.raise_delivery_errors = false
  config.active_support.deprecation = :log
  config.active_record.migration_error = :page_load
  config.assets.debug = true
  config.assets.raise_runtime_errors = true
  config.cache_store = :redis_store, "redis://localhost:6379/0/cache", { expires_in: 90.minutes }
end

1 个答案:

答案 0 :(得分:0)

class Store::ApplicationController < ApplicationController
  helper_method :set_current_store

  private
  def set_current_store
    Rails.logger.debug "set_current_store is called"
    @current_store = Store.find session[:id]
  end
end

class Store::FooController < Store::ApplicationController
  before_action :set_current_store
  def index
    @foos = Foo.where(store_id: @current_store.id)
  end
end