respond_with alternatives in rails 4.2 for backbone

岁酱吖の 提交于 2019-12-07 18:50:17

问题


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

What are the alternatives?


回答1:


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

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.

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.




回答2:


If you follow Bart Jedrocha's suggestion and use jbuilder (it's added by default), then both the respond_* method calls become unnecessary. Here's a simple API I made to test an Android app.

# 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

# views/api/posts/index.json.jbuilder

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


来源:https://stackoverflow.com/questions/28422845/respond-with-alternatives-in-rails-4-2-for-backbone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!