Alex Rivera | Logout

Backbone.js and Rails - How to handle params from Backbone models?

Asked 2011-06-07T21:55:54.473
23

In a standard Rails controller, I'd create a record like this:

@user = User.new(params[:user])

This assumes that the form parameters that come in are nested.

I've been playing with Backbone.js and I noticed that by default, Backbone doesn't nest the parameters the way a normal Rails form might, which is actually something I expected. So I'm wondering what I should do...

Do I

figure out on the server-side if it's a request from Backbone by looking at accepts headers, etc and manipulate the params myself so I can keep my controller code small:

do_some_params_manipulation_with(params)
@user = User.new(params[:user])
respond_to do |format|
  if @user.save
    format.html {redirect_to users_url}
    format.json {render :json => @user.to_json }
  end
end

Or, do I instantiate the object in each branch which ends up with repeated code but might be more maintainable in the long run....

respond_to do |format|
  format.html do
    @user = User.new(params[:user])
    if @user.save
      redirect_to users_url
    end
  end

  format.json do
    @user = User.new(params) # and rely on mass-assignment protection
    if @user.save
      render :json => @user.to_json
    end
  end

end

or do I modify my Backbone.js models by overriding the .toJSON method (which I'm not entirely sure how to do because I don't know enough about Backbone.js yet) so that it nests the params?

In this situation, I have access to both sides of the app, but I am interested in what others are doing.

Edit
Report

1 Answer

1

In one of the answers to Rails mass assignment and Backbone.js there is mentioned patch https://gist.github.com/719080 which I think will do what you need.

answered 2011-06-07T23:02:40.490

Your Answer