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

Ruby On Rails - Active Interaction:如何设置通用类型参数

实现多类型参数的几种方案

针对你在ActiveInteraction中需要支持整数、字符串、浮点数的参数需求,这里有几个实用的实现方式:

方案一:any类型配合自定义验证

先声明参数为any类型,再通过validate方法手动校验类型合法性:

module Api
 module V2
  class MyInteraction < ActiveInteraction::Base
   
   string :sort_string
   array :ids, default: []
   any :mixed_param

   validate :mixed_param_type_check

   private

   def mixed_param_type_check
     unless [Integer, String, Float].include?(mixed_param.class)
       errors.add(:mixed_param, "必须是整数、字符串或浮点数类型")
     end
   end
  end
 end
end

方案二:用custom类型整合校验逻辑

把类型校验直接写在参数声明里,代码更简洁:

module Api
 module V2
  class MyInteraction < ActiveInteraction::Base
   
   string :sort_string
   array :ids, default: []
   custom :mixed_param do |value|
     next if [Integer, String, Float].include?(value.class)
     "必须是整数、字符串或浮点数类型"
   end
  end
 end
end

校验通过返回nil或false,不通过则返回错误提示字符串即可。

方案三:自定义可复用类型(适合多场景使用)

如果多个交互类都需要这种多类型参数,可以扩展ActiveInteraction的类型:

# 在项目初始化文件或单独的类型文件中定义
class MultiType < ActiveInteraction::Type
  def cast(value)
    return value if [Integer, String, Float].include?(value.class)
    super
  end
end

# 在交互类中直接使用自定义类型
module Api
 module V2
  class MyInteraction < ActiveInteraction::Base
   
   string :sort_string
   array :ids, default: []
   multi_type :mixed_param
  end
 end
end

这种方式能减少重复代码,适合需要多次复用该类型校验的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 22:57:26