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

Ruby控制器调用同一方法传不同参数失败问题求助

解决控制器递归调用create_history时参数传递失败的问题

问题根源

  • 无参调用create_history时,方法始终读取请求的原始params,不会使用你构造的第三方检测参数
  • 你构造的参数未按strong params要求包裹在:inspection_request键下,即使传递也会被inspection_request_history_params的require(:inspection_request)拦截

改造方案

1. 修改方法支持自定义参数传入

调整代码,让create_history可以接受外部参数,同时适配强参数规则:

class HomesController < BaseController
  def create_history(custom_params = nil)
    # 优先使用自定义参数,无传入则用请求原始params
    target_params = custom_params || params
    # 基于目标参数生成强参数并创建记录
    inspection_request = @home.inspection_requests.new(inspection_request_history_params(target_params))
    inspection_request.save
    
    if inspection_request.get_paired_inspection.present?
      # 构造第三方检测参数,必须包裹在:inspection_request键下,匹配强参数要求
      third_party_params = {
        inspection_request: {
          request_type: "Third Party",
          third_party_inspection_id: inspection_request.get_paired_inspection.id,
          status: inspection_request.status,
          user_id: inspection_request.user_id,
          requested_at: inspection_request.requested_at
        }
      }
      # 传递自定义参数递归调用
      create_history(third_party_params)
    end
  end

  # 调整强参数方法,支持传入自定义参数源
  def inspection_request_history_params(params_source = params)
    params_source.require(:inspection_request).permit(
      :request_type, :user_id, :requested_at, :performed_at,
      :private_inspection_type_id, :third_party_inspection_id
    )
  end
end

2. 关键改动说明

  • 给create_history增加custom_params可选参数,让方法可接受外部传入的参数
  • 修改inspection_request_history_params,允许传入自定义参数源,不再固定读取请求params
  • 第三方检测参数必须包裹在:inspection_request键下,满足强参数的require校验规则
  • 递归调用时传入构造好的参数,确保第二次执行时使用第三方检测的参数

额外提醒

确认get_paired_inspection方法不会返回永久存在的结果,避免触发无限递归。

内容的提问来源于stack exchange,提问作者SkRoR

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 17:42:15