【发布时间】:2017-06-06 20:43:16
【问题描述】:
我有一个链接控制器,并且我定义了两个自定义操作,称为 upvote 和 downvote。动作定义:-
def upvote
@link = Link.find_by(id: params[:id])
@link.vote_count += 1
flash[:message]="Vote successfully registered"
redirect_to root_path
end
def downvote
@link = Link.find_by(id: params[:id])
@link.vote_count -= 1
flash[:message]="Vote successfully registered"
redirect_to root_path
end
我已经在 routes.rb 文件中添加了这些操作的路由:-
post '/links/:id', to: 'links#upvote', as: 'upvote'
post '/links/:id', to: 'links#downvote', as: 'downvote'
rails 路线显示:-
upvote POST /links/:id(.:format) links#upvote
downvote POST /links/:id(.:format) links#downvote
我正在调用视图中的操作,如下所示:-
<% if link.user != current_user %>
<span class="vote-buttons">
<div class="btn-group-vertical" role="group" aria-label="vote-buttons">
<%= button_to 'Up', 'upvote_path', type:"button", class:"btn btn-xs btn-success" %>
<%= button_to 'Down', 'downvote_path', type:"button", class:"btn btn-xs btn-danger" %>
</div>
</span>
<% end %>
但我不断收到此错误:-
No route matches [POST] "/upvote_path"
为什么即使 rails routes 显示该路线存在,我也会看到这个?
我也试过重启服务器。
【问题讨论】:
-
您将其定义为发布请求,那么为什么要在路由中包含 :id,您可以像这样简单地定义它 => post '/links', to: 'links#upvote', as: 'upvote' 并像 upvote_path 一样使用它
-
我需要在 upvote/downvote 操作中使用参数中的链接 ID。
-
所以让它 GET 请求,像这样 => 获取 '/links/:id', to: 'links#upvote', as: 'upvote' 并像这样使用它 => upvote_path(id : 链接.id)
-
如果有效请告诉我
-
刚试过这个,我得到“错误的URI(不是URI?):upvote_path(id:link.id)”
标签: ruby-on-rails