Rails Grape 中如何使用 respond_to

lzm420241 · April 08, 2016 · Last by justin replied at April 08, 2016 · 2690 hits

我用 grape 写的 api 采用 respond_to 的方式

respond_to do |format|
            format.js do
              render :json => {results: {coupon: {title: @user_coupon.title, value: @coupon_value, end_date: @end_date}}, statusCode: 200, statusMsg: "恭喜你成功获取优惠券", success: true}, :callback => params[:callback]
            end
      end

然后调用这个 api,服务器返回 500,看了 log 后发现

NoMethodError (undefined method `respond_to' for #<#<Class:0x0000000393f4b0>:0x000000057c3878>):

grape 集成在 rails,为什么不可以没有定义 respond_to 这个方法呢?

就是没那个方法啊,Rails 也包含好多部分,Grape 只是挂在了 Rails 的服务上,但 respond_to 是有 ActionController 提供的

用了 grape 一般是用来返回接口数据吧。接口数据一般是字符串 或 json 吧。你上面 format.js 是个什么情况。。。

format :json
get 'jsondata' do
  {results: {coupon: {title: @user_coupon.title, value: @coupon_value, end_date: @end_date}}, statusCode: 200, statusMsg: "恭喜你成功获取优惠券", success: true}
end

grape 写接口这么干就好了哈 https://github.com/ruby-grape/grape

grape返回数据,推荐使用 grape-entity

You need to Sign in before reply, if you don't have an account, please Sign up first.