加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – 如何在Grape中定义哈希数组?

发布时间:2020-12-17 03:33:01 所属栏目:百科 来源:网络整理
导读:我使用Ember作为我的前端和Grape API来提供我的API. 前端发送类似的东西: { "service"={ "name"="Name","duration"="30","user"=nil,"organization"="org","category"=nil,"description"="description","disabled"=true,"color"=nil,"availabilities"=[ { "
我使用Ember作为我的前端和Grape API来提供我的API.

前端发送类似的东西:

{
  "service"=>{
    "name"=>"Name","duration"=>"30","user"=>nil,"organization"=>"org","category"=>nil,"description"=>"description","disabled"=>true,"color"=>nil,"availabilities"=>[
      {
        "day"=>"Saturday","enabled"=>false,"timeSlots"=>[
          {
            "startAt"=>"09:00 AM","endAt"=>"05:00 PM"
          }
        ]
      },{
        "day"=>"Sunday",{
        "day"=>"Monday","enabled"=>true,"endAt"=>"05:00 PM"
          },{
            "startAt"=>"05:00 AM","endAt"=>"09:00 PM"
          },"endAt"=>"09:00 PM"
          }
        ]
      },{
        "day"=>"Tuesday",{
        "day"=>"Wednesday",{
        "day"=>"Thursday",{
        "day"=>"Friday","endAt"=>"05:00 PM"
          }
        ]
      }
    ]
  }
}

我正在努力实现Grape api接口来接收有效载荷,我最终得到了类似的东西:

resource :services do
    params do
      requires :service,type: Hash do
        requires :name,type: String
        requires :organization,type: String
        requires :duration,type: Integer
        requires :category,type: String
        optional :color,type: String
        optional :description,type: String
        optional :disabled,type: Boolean
        requires :availabilities,type: Array do
          requires :day,type: String
          optional :enabled,type: Boolean
          optional :timeSlots,type: Array do
            requires :startAt,type: Time
            requires :endtAt,type: Time
          end
        end
      end
    end
    post do
      puts params
    end
  end

但没有运气,因为我收到以下错误:

ERROR -- service[availabilities][0][timeSlots][0][endtAt] is missing

解决方法

您可以尝试使用“group”来指示数组元素的类型.

示例(更新):

params do
  group :services,type: Array,desc: "An array of services" do
    requires :name,type: String
    requires :organization,type: String
    requires :duration,type: Integer
    ...
  end
end
put '/test' do
  s = []
  params[:services].each do |service|
    s << service
  end
  return s
end

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读