respond_with alternatives in rails 4.2 for backbone
Asked Answered
P

2

5

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?

Purnell answered 10/2, 2015 at 1:59 Comment(0)
M
10

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.

Merrow answered 10/2, 2015 at 3:15 Comment(0)
A
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
Althing answered 7/3, 2015 at 3:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.