本文介绍了Rails 4.2中骨干网的response_with替代品的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在导轨4.2中,respond_withrespond_to已移至responders gem.我读过,这不是最佳实践.我的应用程序使用backbone.js.

In rails 4.2 respond_with and respond_to have been moved to the responders gem. I've read that this is not the best practice. I use backbone.js for my app.

为了渲染控制器中的所有用户,我使用:

For render all users in controller I use:

class UsersController < ApplicationController
  respond_to :json

  def index
    @users = User.all

    respond_with @users
  end
end

有哪些替代方案?

推荐答案

只有respond_with和类级别respond_to已被删除,如此处.您仍然可以像往常一样使用实例级别respond_to

It's only respond_with and the class level respond_to that have been removed as indicated here. You can still use the instance level respond_to as always

class UsersController < ApplicationController
  def index
    @users = User.all

    respond_to do |wants|
      wants.json { render json: @users }
    end
  end
end

话虽这么说,将响应者gem添加到您的项目中并像您的示例中那样继续编写代码绝对没有错.将这种行为提取到单独的gem中的原因是,许多Rails核心成员并不认为它属于主要的Rails API. 来源.

That being said, there is absolutely nothing wrong with adding the responders gem to your project and continuing to write the code like in your example. The reason for extracting this behavior into a separate gem is that many Rails core members didn't feel it belonged in the main Rails API. Source.

如果您正在寻找更强大的功能,请看一下用于返回JSON结构的模板选项,例如默认情况下,Rails 4.2中包含的jbuilder rabl 中包含的.希望这会有所帮助.

If you're looking for something more robust, take a look at the host of templating options for returning JSON structures like jbuilder which is included with Rails 4.2 by default or rabl. Hope this helps.

这篇关于Rails 4.2中骨干网的response_with替代品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 10:48