如何在Rails中生成引用父级同对象的嵌套路由?
解决方案
在Rails中,你可以通过嵌套member路由实现需求——因为pricing是依附于单个Appointment的资源,不需要独立ID。直接在现有resources :appointments块内添加自定义member路由即可:
resources :appointments do member do # GET 请求对应编辑页面 get 'pricing/edit', to: 'pricing#edit' # PATCH/PUT 请求对应更新操作 patch 'pricing/update', to: 'pricing#update' put 'pricing/update', to: 'pricing#update' end end
说明:
member块会自动继承父资源的:id参数,生成的路由完全匹配你的需求:GET /appointments/:id/pricing/edit→ 映射到PricingController#editPATCH/PUT /appointments/:id/pricing/update→ 映射到PricingController#update
- 如果你的更新逻辑只需要支持一种HTTP方法,可以只保留
patch或put(Rails推荐用patch做资源部分更新)。
控制器示例:
在PricingController中,直接通过params[:id]获取对应的Appointment实例(路由中的:id就是父资源的ID):
class PricingController < ApplicationController def edit @appointment = Appointment.find(params[:id]) # 假设 Appointment 和 Pricing 是一对一关联 @pricing = @appointment.pricing end def update @appointment = Appointment.find(params[:id]) if @appointment.pricing.update(pricing_params) redirect_to @appointment, notice: '定价更新成功' else render :edit end end private def pricing_params params.require(:pricing).permit(:amount, :currency, ...) # 根据你的业务字段调整 end end
内容的提问来源于stack exchange,提问作者Sam Stickland
相关产品推荐
相关产品推荐

