Reputation: 7043
I'm trying to get the routing right when using link_to to update attribute through a controller:
view (@orders.each)
<%= link_to 'Cancel', controller: :orders, action: 'cancel_order', id: order.id %>
OrdersController
def cancel_order
@order = Order.find(params[:id])
@order.update_attribute(status: 0)
redirect_to root_url
end
No matter what I do with my routes, I get this error:
No route matches {:action=>"cancel_order", :controller=>"orders", :id=>1}
Please help!
Upvotes: 0
Views: 278
Reputation: 11421
routes.rb
1st case
resources :orders do
member do
get :cancel #output path - cancel_orders/:id
end
end
or 2nd case
get 'cancel_order/:id' => 'orders#cancel_order', as: :cancel_order
output path: cancel_order/:id
:
1 link: <%= link_to 'Cancel', cancel_orders_path(order) %>
2 link: <%= link_to 'Cancel', cancel_order_path(order) %>
Upvotes: 1
Reputation: 724
I gave it a shot. I am not sure which version of Rails are you using. Here is my code snippet
My cancel_order
method
def cancel_order
@order = Order.find params[:id]
@order.update_attributes status: true
redirect_to root_url
end
My show.html.erb
<%= link_to 'Cancel', cancel_order_order_path(@order), :method => :post %>
My routes.rb
resources :orders do
member do
post 'cancel_order'
end
end
There are other way to achieve working routing but this feels cleaner to me. It would be easier to figure out your issue if you post your routes configuration. I hope this helps you.
Upvotes: 1