Rails Grape 中如何使用 respond_to

lzm420241 · 2016年04月08日 · 最后由 justin 回复于 2016年04月08日 · 2693 次阅读

我用 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

需要 登录 后方可回复, 如果你还没有账号请 注册新账号