2015-02-10 60 views
2

在rails 4.2中respond_withrespond_to已被移至responders gem。我读过这不是最佳做法。我使用backbone.js作为我的应用程序。respond_with rails 4.2中的替代骨干

对于渲染器的所有用户使用:

class UsersController < ApplicationController 
    respond_to :json 

    def index 
    @users = User.all 

    respond_with @users 
    end 
end 

有什么选择?

回答

7

它只是respond_with和级别respond_to已被删除,如指示here。您仍然可以使用实例级别respond_to一如既往

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

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

话虽这么说,是绝对没有错,加上反应宝石到您的项目,继续编写类似的代码在你的榜样。将这种行为解压到单独的gem中的原因是,许多Rails核心成员并不觉得它属于主要的Rails API。 Source

如果您正在寻找更强大的功能,请查看模板选项的主机以返回默认包含在Rails 4.2中的jbuilderrabl等JSON结构。希望这可以帮助。

2

如果您按照Bart Jedrocha的建议并使用jbuilder(默认情况下会添加它),那么respond_*方法调用就不再需要了。以下是我测试Android应用的一个简单API。

# controllers/api/posts_controller.rb

module Api 
    class PostsController < ApplicationController 

    protect_from_forgery with: :null_session 

    def index 
     @posts = Post.where(query_params) 
          .page(page_params[:page]) 
          .per(page_params[:page_size]) 
    end 

    private 

    def page_params 
     params.permit(:page, :page_size) 
    end 

    def query_params 
     params.permit(:post_id, :title, :image_url) 
    end 

    end 
end 

# routes.rb

namespace :api , defaults: { format: :json } do 
    resources :posts 
end 

​​

json.array!(@posts) do |post| 
    json.id  post.id 
    json.title  post.title 
    json.image_url post.image_url 
end