如何在Rails中实现预约请求审批?路由与链接配置疑问
Got it, let's fix this step by step. You're almost there—just need to adjust your routes and link_to to align with Rails' REST conventions, plus a small tweak to your controller for better robustness.
1. Configure the Route Correctly
Since approving a booking targets a single existing booking, we need to add a member route to your resources :bookings block. This maps the action to a URL with the booking ID (like /bookings/1/approve) and uses the proper HTTP verb for partial resource updates:
# config/routes.rb Rails.application.routes.draw do # ... other routes ... resources :bookings do # Use PATCH because we're only updating the `state` field, not the entire booking patch :approve, on: :member end end
You can confirm this works by running rails routes in your terminal—you'll see a line like:
approve_booking PATCH /bookings/:id/approve(.:format) bookings#approve
2. Refine the Controller Method
Your current controller code has two minor gaps:
- If
Booking.find_by_id(params[:id])returnsnil(e.g., invalid ID), calling@booking.updatewill throw an error. - Checking
@booking.state == "approved"after update is redundant—updatealready returns a boolean indicating success.
Here's a more robust version:
def approve @booking = Booking.find_by_id(params[:id]) if @booking&.update(state: "approved") flash[:success] = "Booking successfully approved" else # Adjust error message to cover both missing bookings and update failures flash[:error] = "Failed to approve booking: either it doesn't exist or there was an issue updating it" end redirect_to bookings_path end
The &. (safe navigation operator) prevents errors if @booking is nil—it skips the update call and jumps straight to the else block.
3. Fix the link_to Helper
Your original link uses the wrong path helper and doesn't specify the HTTP method. Since we defined a PATCH route, we need to:
- Use the correct path helper:
approve_booking_path(booking)(from therails routesoutput) - Add
method: :patchto tell Rails to send a PATCH request (browsers only support GET/POST natively, so Rails generates a hidden form to simulate PATCH)
Updated ERB code:
<td><%= link_to 'Approve', approve_booking_path(booking), method: :patch, class: "button-xs success" %></td>
That's all! Now when you click the "Approve" button, it will send a PATCH request to the correct URL, trigger your controller's approve method, update the booking's state, and redirect back to the bookings list with the appropriate flash message.
内容的提问来源于stack exchange,提问作者jungleMan

