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

如何在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#edit
    • PATCH/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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 17:23:12