【问题标题】:How to add another method in rails controller如何在 Rails 控制器中添加另一种方法
【发布时间】:2013-03-27 04:31:35
【问题描述】:

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

ma​​tches_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

routes.rb

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

current.json.rabl

collection @match
   attributes :id,:live

Rake 路线

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>'

application.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

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

【问题讨论】:

  • 哪个部分不工作?您是否收到“无路线”错误? rake routes 输出什么?
  • 我已经编辑了我的问题,请立即查看
  • 您的错误是指您未包含的文件:application_controller.rb。请出示该文件。
  • application.rb 现已添加,请查看
  • 您似乎无法从 rescue_from 块访问flash 变量,尽管我从未尝试过。

标签: ruby-on-rails json ruby-on-rails-3 rabl rails-api


【解决方案1】:

您不能在直接传递给rescue_from 的块内访问flash。但是,如果您传递异常处理程序方法的符号,则可以访问 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

有关详细信息,请参阅 rescue_from 上的 ActionController Rails Guide 部分。

【讨论】:

  • 您的原始错误引用了application_controller.rb:6:in 'block in &lt;class:ApplicationController&gt;',但是根据我上面的更改,不应再在第 6 行将块传递给rescue_from。您是否删除了该块?或者您是否需要重新启动应用程序?
猜你喜欢
  • 2013-06-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-22
  • 1970-01-01
相关资源
最近更新 更多