简体   繁体   English

Ruby on Rails:link_to调用控制器中的自定义方法-match方法给出错误

[英]Ruby on Rails: link_to calls custom method in controller - match method is giving error

I want to call the method "link_to" that once called - changes an attribute value of an item. 我想调用一次调用的方法“ link_to”-更改项目的属性值。 So when the user calls the linked_to method for an 'item' the closed attribute for that item will change from item.close = false -> item.close = true 因此,当用户为“项目”调用linked_to方法时,该项目的关闭属性将从item.close = false-> item.close = true更改

<% @items.each do |i| %>
    ...
<%= link_to "Close", item_close_path(:id => i.id) %>
    ...
<% end %>

Within my controller method I have: 在我的控制器方法中,我有:

def close
    Item.find(params[:id]).close = true

 #redirect_to index
  end

Within my routes method I have: 在我的路线方法中,我有:

match 'items/:id/close' => 'items#close', as: :items_close

The error I'm getting is: 我得到的错误是:

RuntimeError: You should not use the match method in your router without specifying an HTTP method RuntimeError:如果未指定HTTP方法,则不应在路由器中使用match方法

You must specify a HTTP method (GET, POST, PATCH, PUT, DELETE, etc.). 您必须指定HTTP方法(GET,POST,PATCH,PUT,DELETE等)。 It looks like you are trying to update your Item (although it won't work, since you are not saving here). 看来您正在尝试更新自己的商品(尽管它无法正常工作,因为您没有在此处保存)。 In the case of an update you want to use PATCH or PUT. 如果是更新,则要使用PATCH或PUT。 I recommend to use PATCH for updates, since this is the Rails convention ( read here ). 我建议使用PATCH进行更新,因为这是Rails约定(请参阅此处 )。

You can do it like this: 您可以这样做:

match 'items/:id/close' => 'items#close', via: [:patch, :put], as: :items_close

You could also use 'patch' instead of 'match', which is cleaner if you are only using PATCH for this route: 您也可以使用'patch'而不是'match',如果您仅对此路径使用PATCH,则此方法更干净:

patch 'items/:id/close' => 'items#close', as: :items_close

In the link you must also specify the HTTP method (if it's other than GET), this is how: 在链接中,您还必须指定HTTP方法(如果不是GET),方法如下:

<%= link_to "Close", item_close_path(:id => i.id), method: :patch %>

More info on 'match' here 有关“匹配”的更多信息,请点击此处

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM