【问题标题】:Defined a custom action in controllers and added routes but still get no route matches error. Rails 5 app在控制器中定义了一个自定义操作并添加了路由,但仍然没有路由匹配错误。 Rails 5 应用程序
【发布时间】: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


【解决方案1】:

没有路线匹配 [POST] "/upvote_path"

根据您的路线,您缺少应该在路线内发送的:id

<%= button_to 'Up', upvote_path(link), type:"button", class:"btn btn-xs btn-success" %>

同样适用于 downvote

<%= button_to 'Down', downvote_path(link), type:"button", class:"btn btn-xs btn-danger" %>

除了上述问题之外,您在 upvotedownvote

之后没有保存 @link
def upvote
  @link = Link.find_by(id: params[:id])
  @link.vote_count += 1
  @link.save!
  flash[:message]="Vote successfully registered"
  redirect_to root_path
end

def downvote
  @link = Link.find_by(id: params[:id])
  @link.vote_count -= 1
  @link.save!
  flash[:message]="Vote successfully registered"
  redirect_to root_path
end

【讨论】:

  • 试过这个。仍然相同的错误:- 在 2017-06-06 18:10:36 +0530 ActionController::RoutingError 开始 POST "/upvote_path(link)" for ::1 (没有路由匹配 [POST] "/upvote_path(link)") :
  • @rawcode 你注意到我删除了upvote_path(link) 周围的引号吗?用这个再试一次!
  • facepalm 哎呀,引文太痛苦了。非常感谢帕万!
【解决方案2】:
<%= button_to 'Up', 'upvote_path', ...

此处按钮的 URL 实际上是 "upvote_path"。当然,这个网址不存在。我想你的意思是这样的:

<%= button_to 'Up', upvote_path(link), ...

【讨论】:

  • @pavan 提出了同样的建议,我试过了。还是一样的错误。
  • @rawcode:“还是同样的错误。” - 我不这么认为。您没有注意到引号或没有仔细阅读答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-19
  • 2019-03-24
相关资源
最近更新 更多