简体   繁体   中英

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. 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

<% @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

You must specify a HTTP method (GET, POST, PATCH, PUT, DELETE, etc.). 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. I recommend to use PATCH for updates, since this is the Rails convention ( read here ).

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 '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:

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

More info on 'match' here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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