控制器方法#show被调用

时间:2015-06-04 01:47:58

标签: ruby-on-rails ruby controller

我的#index视图上有一个链接:

<%= link_to 'Export Calendar (ICS)', { controller: :tickets, action: :ics_export, format: :ics }, class: "class-needed right" %>

routes.rb与此相关:

resources :tickets
get 'tickets/calendar' => 'tickets#ics_export'
post 'tickets' => 'tickets#index'
patch 'tickets/:id/close' => 'tickets#close', as: 'close_ticket'
post 'tickets/:id' => 'ticket_comments#create'

我的TicketsController相关:

before_action :set_ticket, only: [:show, :edit, :destroy, :update, :close]

def show
  @ticket_comment = TicketComment.new
end

def ics_export
  tickets = Ticket.all
  respond_to do |format|
    format.html
    format.ics do
      cal = Icalendar::Calendar.new
      tickets.each do |ticket|
        event = Icalendar::Event.new
        event.dtstart = ticket.start
        event.description = ticket.summary
        cal.add_event(event)
      end
      cal.publish
      render :text =>  cal.to_ical
    end
  end
end

private
def set_ticket
  @ticket = Ticket.find(params[:id])
end

当我点击链接时,我需要/tickets/calendar.ics这是正确的,但我收到以下错误:

ActiveRecord::RecordNotFound in TicketsController#show

Couldn't find Ticket with 'id'=calendar

Extracted source (around line #83):

 private
 def set_ticket
   @ticket = Ticket.find(params[:id])
 end

突出显示@ticket = Ticket.find(params[:id])。有意义的是,它无法调用id为calendar的票证。

请求有参数:

{"id"=>"calendar", "format"=>"ics"}

如何修复此错误?为什么要调用show动作?

1 个答案:

答案 0 :(得分:4)

规范Rails Routing from the Outside In中有一个脚注:

  

Rails路由按照指定的顺序进行匹配,因此如果您有资源:获取'photos / poll'之上的照片,资源行的show action路线将在获取行之前匹配。要解决此问题,请将获取行移到资源行上方,以便首先匹配。

如评论所述,修复方法是在get 'tickets/calendar' => ...之前指定resources :tickets。如果路线的顺序有问题,您可以运行rake routes,据我所知,这应该按照检查的顺序呈现您的路线。