You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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]) returns nil (e.g., invalid ID), calling @booking.update will throw an error.
  • Checking @booking.state == "approved" after update is redundant—update already 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.

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 the rails routes output)
  • Add method: :patch to 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:03:37