Search code examples
ruby-on-railsrubyrouteslink-toupdate-attribute

Rails: Route Error while trying to update attribute through link_to


ERROR: No route matches [GET] "/bookings/:id/%3E:format"

I want to update an attribute when click on link of 'link_to'..

<%= link_to 'Cancel', '/bookings/:id/(.:format)' %>

routes.rb

put '/bookings/:id/(.:format)' => "bookings#tocancel"
patch '/bookings/:id/(.:format)' => "bookings#tocancel"

controller

def tocancel
 @booking = Booking.find(params[:id])
 @booking.update_attribute(:status, "cancel")
 respond_to do |format|
  format.html { redirect_to @booking, notice: 'Booking was successfully cancelled.' }
  format.json { render :show, status: :ok, location: @booking }

end


Solution

  • create a method in bookings controller as:

    def tocancel
     @booking = Booking.find(params[:id])
     @booking.update_attribute(:status, "cancel")
     respond_to do |format|
      format.html { redirect_to @booking, notice: 'Booking was successfully cancelled.' }
      format.json { render :show, status: :ok, location: @booking }
     end
    end
    

    Routes for this would be:

    resources :bookings do
      member do
       get :tocancel
      end
    end
    

    Cancel link can be created as:

    link_to "Cancel", tocancel_booking_path(booking.id)
    

    Here you should have booking_id passed to cancel link. Now check how you get booking_id on the page where you put this cancel link. Let me know if any issue.