1

我在向控制器添加新方法时遇到问题,以下是详细信息:

match_controller.rb

def index
  @matches = Match.all    
  render rabl: @matches
end

def current
  @matches = Match.find_by_sql("SELECT * FROM `TEST`.`matches` where live=1;")    
  render rabl: @matches
end

路线.rb

resources :matches, defaults: {format: :json}, except: :edit do 
  collection do
    get :current
  end
end

current.json.rabl

collection @match
   attributes :id,:live

耙路线

current_matches GET    /matches/current(.:format) matches#current {:format=>:json}
        matches GET    /matches(.:format)         matches#index {:format=>:json}
                POST   /matches(.:format)         matches#create {:format=>:json}
      new_match GET    /matches/new(.:format)     matches#new {:format=>:json}
          match GET    /matches/:id(.:format)     matches#show {:format=>:json}
                PUT    /matches/:id(.:format)     matches#update {:format=>:json}
                DELETE /matches/:id(.:format)     matches#destroy {:format=>:json}

日志中的错误

NameError (undefined local variable or method `flash' for #<MatchesController:0x0000000d7b2368>):
app/controllers/application_controller.rb:6:in `block in <class:ApplicationController>'

应用程序.rb

class ApplicationController < ActionController::API
   include ActionController::MimeResponds
   include CanCan::ControllerAdditions

  rescue_from CanCan::AccessDenied do |exception|
    flash[:error] = exception.message
    puts exception.message
    redirect_to root_url
  end

  def log_exception(exception)
    logger.error(exception.message)
    logger.error(exception.backtrace.join("\n"))
  end
end

我以前在另一个应用程序中做过这个,我不知道为什么它在这里不起作用。

4

1 回答 1

1

您不能flash在直接传递给rescue_from. 但是,flash如果您传递异常处理程序方法的符号,则可以访问。例如:

class ApplicationController < ActionController::API
  rescue_from CanCan::AccessDenied, :with => :access_denied

  private

  def access_denied(exception)
    flash[:error] = exception.message
    redirect_to root_url
  end
end

有关详细信息,请参阅ActionController Rails 指南部分。rescue_from

于 2013-03-27T05:35:20.533 回答