Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

respond_with alternatives in rails 4.2 for backbone

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?

like image 617
colmer Avatar asked Feb 10 '15 01:02

colmer


1 Answers

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.

like image 62
Bart Jedrocha Avatar answered Oct 05 '22 23:10

Bart Jedrocha