• If you are citizen of an European Union member nation, you may not use this service unless you are at least 16 years old.

  • You already know Dokkio is an AI-powered assistant to organize & manage your digital files & messages. Very soon, Dokkio will support Outlook as well as One Drive. Check it out today!

View
 

Todos 06-Building with Rails

This version was saved 13 years, 9 months ago View current version     Page history
Saved by Dr. Baba Kofi Weusijana
on June 17, 2010 at 9:21:27 am
 

About Rails

 

From its site: "Ruby on Rails is an open-source web framework that's optimized for programmer happiness and sustainable productivity. It lets you write beautiful code by favoring convention over configuration."

 

Installation

 

Make sure you have installed Rails 2.3.4 or above and the sqlite gem

 

$ sudo gem install sqlite3-ruby
$ sudo gem install rails

 

Create the project

A small rails application will serve as a backend for the Todos application.

 

Create a new Todos app by entering the following command into the console:

 

$ rails todos
$ cd todos

 

Make sure that you do issue this command outside your SproutCore application folder!

 

Setup the data model

 

We can use Rails generators to greate a basic RESTful interface for the Task model by typing

 

$ script/generate scaffold Task description:string isDone:boolean order:integer
 

Now you need to update your database to conform the model. For that, type

 

$ rake db:migrate
 

Adjust JSON communication

 

Sproutcore uses the field guid for objects ids, but Rails calls this field id.

 

You have two options on how to convert between these naming conventions:

 

Option 1: Adjust Rails JSON output

 

To customize the JSON output of an object, write a json_to_task protected method just before the last "end" line in TasksController (app/controllers/tasks_controller.rb): 

 

  protected
  def json_for_task(task)
    { :guid => task_path(task),
      :description => task.description,
      :isDone => task.isDone
    }
  end

Option 2: Set primaryKey in your Sproutcore model class

 

You can subclass SC.Record and set the primaryKey of your sublcass to "id". Your Todo-Object then needs to extend from e.g. App.Rails.Record.

 

App.Rails.Record = SC.Record.extend({
  primaryKey : "id" // Extend your records from App.Rails.Record instead of SC.Record.
});

 

(Thanks to Giacomo Luca Maioli for this idea.)

 

This tutorial sticks to Option 1. The rails-code for option 2 is the same, just omit calling json_for_task().

 

Writing the controller

 

Open the file app/controllers/tasks_controllers.rb, and modify the index method like this:

 
def index
  @tasks = Task.all

  respond_to do |format|
    tasks = @tasks.map {|task| json_for_task(task) }
    format.json { render :json => { :content => tasks } }
    format.html
    format.xml  { render :xml => @tasks }
  end
end
 

Start the server from the Rails app directory:

 

$ script/server

 

To fill your database, create some tasks by visiting http://localhost:3000/tasks and entering some test data.

 

To test your server now, open the following address in your web browser: http://localhost:3000/tasks?format=json. You should receive a plain-text-file, with the datafields of your test data. 

 

Implementing CRUD operations

 

The following sections show how to implement the CRUD (create, read, update, delete) operations for our Task model.

 

We will start with read (or also GET), as it is the easiest. Extend the code like this:

 

Read or GET Task

 

  def show
    @task = Task.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @task }
      format.json do
        render :json => {
          :content => json_for_task(@task),
          :location => task_path(@task)
        }
      end
    end
  end

 

Try the outcome by calling http://localhost:3000/tasks/show/1?format=json.

 

Create Task

 

 

  def create
    @task = Task.new(params[:task])

    respond_to do |format|
      if @task.save
        flash[:notice] = 'Task was successfully created.'
        format.json do
          render :json => { :content => json_for_task(@task) }, :status => :created,
                            :location => task_path(@task)
        end
        format.html { redirect_to(@task) }
        format.xml  { render :xml => @task, :status => :created, :location => @task }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @task.errors, :status => :unprocessable_entity }
      end
    end
  end

Update Task

 

  def update
    @task = Task.find(params[:id])

    respond_to do |format|
      params[:task].delete(:guid)
      if @task.update_attributes(params[:task])
        flash[:notice] = 'Task was successfully updated.'
        format.json do
          render :json => { :content => json_for_task(@task) }, :location => task_path(@task)
        end
        format.html { redirect_to(@task) }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @task.errors, :status => :unprocessable_entity }
      end
    end
  end

Delete Task

 
  def destroy
    @task = Task.find(params[:id])
    @task.destroy

    respond_to do |format|
      format.json { head :ok }
      format.html { redirect_to(tasks_url) }
      format.xml  { head :ok }
    end
  end

 

Customize the data source

 

To fullfill Ruby on Rails expectations, modify the send() call in the createRecord and updateRecord in the data_source/task.js file in your SproutCore project like this:

 

.send({ task: store.readDataHash(storeKey) });

Setup your proxy

 

Add the following line to the Buildfile file in your SproutCore project:

proxy "/tasks", :to => "localhost:3000"

You’re Done!

 

Continue to next step: Step 7: Hooking Up to the Backend »

Comments (0)

You don't have permission to comment on this page.