控制器方法#show 被调用 [英] Controller method #show getting called
问题描述
我的 #index
视图中有一个链接:
I have a link on my #index
view:
<%= 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
,这是正确的,但出现以下错误:
And when I click the link, it takes me to /tickets/calendar.ics
which is correct but I get the following error:
ActiveRecord::RecordNotFound in TicketsController#show
找不到'id'=calendar
提取的源代码(围绕第 83 行):
private
def set_ticket
@ticket = Ticket.find(params[:id])
end
@ticket = Ticket.find(params[:id])
突出显示.这是有道理的,它无法调用具有 calendar
id 的票证.
The @ticket = Ticket.find(params[:id])
is highlighted. Which make sense that it is failing to call a ticket with an id of calendar
.
请求有参数:
{"id"=>"日历","格式"=>"ics"}
我该如何解决这个错误?为什么要调用 show 动作?
How do I fix this error? Why is it calling the show action?
推荐答案
在规范的 Rails 中有一个脚注从外到内的路由到效果:
Rails 路由按照它们指定的顺序进行匹配,因此如果您在 get 'photos/poll' 上方有一个 resources :photos,则资源行的 show action 路由将在 get 行之前匹配.要解决此问题,请将 get 行移动到资源行上方,使其首先匹配.
Rails routes are matched in the order they are specified, so if you have a resources :photos above a get 'photos/poll' the show action's route for the resources line will be matched before the get line. To fix this, move the get line above the resources line so that it is matched first.
正如所评论的,修复方法是指定 get 'tickets/calendar' =>...
在 resources :tickets
之前.如果路线顺序有问题,您可以运行 rake routes
,据我所知,它应该按照检查的顺序呈现您的路线.
As commented, the fix is to specify get 'tickets/calendar' => ...
ahead of resources :tickets
. If the order of routes is in question, you can run rake routes
, which, to the best of my knowledge, should render your routes in the order they are checked.
这篇关于控制器方法#show 被调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!