Skip to content

Instantly share code, notes, and snippets.

@ahhqx
Created August 2, 2011 04:32
Show Gist options
  • Save ahhqx/1119608 to your computer and use it in GitHub Desktop.
Save ahhqx/1119608 to your computer and use it in GitHub Desktop.
Rails 3.0.9 model/controller ready to use with Backbonejs

Do not include root in json

Add ActiveRecord::Base.include_root_in_json = false in an initializer (or config/environment.rb)

Model

Model should use attr_accessible in order to filter the parameter correctly In the example we use the model Task which only accessible attribute : name

Controller

Html

Work as usual (cf tests)

JSON

It should use params to create a new model, it should NOT use params[:model_name] (default when using scaffolding) (cf tests) We change params[:task] to params in the controller create method

class Task < ActiveRecord::Base
attr_accessible :name
end
class TasksController < ApplicationController
# ...
# POST /tasks
# POST /tasks.xml
def create
respond_to do |format|
format.html { @task = Task.new(params[:task])}
format.xml { @task = Task.new(params[:task])}
format.json { @task = Task.new(params)}
end
# Create a new task accroding to the type
respond_to do |format|
if @task.save
format.html { redirect_to(@task, :notice => 'Task was successfully created.') }
format.xml { render :xml => @task, :status => :created, :location => @task }
format.json { render :json => @task, :status => :created, :location => @task }
else
format.html { render :action => "new" }
format.xml { render :xml => @task.errors, :status => :unprocessable_entity }
format.json { render :json => @task.errors, :status => :unprocessable_entity }
end
end
end
# ...
end
require 'test_helper'
class TasksControllerTest < ActionController::TestCase
# ...
test "html should create task" do
the_task_name = "Super task"
assert_difference('Task.count') do
post :create, :format => :html, :task => {:name => the_task_name}
end
assert_equal the_task_name, Task.last.name
assert_redirected_to task_path(assigns(:task))
end
test "json should create task" do
the_task_name = "Super task"
assert_difference('Task.count') do
post :create, :format => :json, :name => the_task_name
end
assert_equal the_task_name, Task.last.name
end
# ...
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment