2015-02-10 69 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