react_with 在 rails 4.2 中的替代方案用于主干 [英] respond_with alternatives in rails 4.2 for backbone

查看:22
本文介绍了react_with 在 rails 4.2 中的替代方案用于主干的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Rails 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 结构的模板选项的主机,例如 jbuilder 默认包含在 Rails 4.2 或 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.

这篇关于react_with 在 rails 4.2 中的替代方案用于主干的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆