Rails 4 - Respond only to JSON and not HTML

前端 未结 10 1197
栀梦
栀梦 2020-12-08 02:59

I\'m trying to build an API in rails 4, and am having an issue where rails returns a 500 error instead of a 406 when using respond_to :json and trying to access

10条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-08 03:26

    In Rails 4, you need to pass a lambda to enforce the constraint on a route.

    Unfortunately, this will NOT work because it will still try to serve up (or attempt to serve up) an html template since the format is an optional parameter:

    resources :posts, constraints: { format: 'json' }
    

    This DOES work (uses the lambda):

    resources :posts, constraints: lambda { |req| req.format == :json }
    

    See the second (final) note in this section of the Rails guide.

提交回复
热议问题