Skip to content
m3talsmith edited this page Apr 18, 2013 · 7 revisions

Overview

Restful Model is based on how I use Ruby on Rails; be it ActiveRecord or Mongoid. As such, there are two steps to having an instance ready to use.

The first step is to define your Model. That's what generate is for.

Generating a Model

Now that you've seen the options, here's how to generate a Model:

var User = RestfulModel.generate({className: 'User'});

Options

There a growing list of options for generating a model:

  • className: 'User' (required)
  • fields: ['name', 'age', 'gender'] (optional)
  • fieldsReadOnly: ['age'] (optional)
  • baseUrl: '/users' (optional)
  • requiredData: {format: 'json', favoriteColor: 'pink'} (optional)
  • hooks: {getName: function(){return this.name;}} (optional)

fields

The fields option allows you to define what fields you're expecting from various functions like new, build, find, save, update, create, and all. If you leave these out, Restful Model will assume that all the data belongs with the model. If you provide them, Restful Model will not include any keys outside of those fields.

fieldsReadOnly

The fieldsReadOnly option represents an array of fields that you don't want updated on the server. There are several reasons for doing this. For example, perhaps you need an model's saved id, but when you go to update the model, you don't want that id changed.

baseUrl

Restful Model will use the baseUrl for any restful ajax actions. If you leave this out, we'll assume you just want the className as the url.

For example when using Model#all:

var User = RestfulModel.generate({className: 'User'});
User.all();

User.all would attempt a GET request to /users. Whereas with baseUrl:

var User = RestfulModel.generate({className: 'User', baseUrl: '/admin/users'});
User.all();

User.all would attempt a GET request to /admin/users. It is always best to take the assumption out of the question.

requiredData

The purpose of the requiredData options is so that you can have extra data sent with ajax requests; perhaps you have to send back an authentication token or format, or perhaps some analytics tracking code - this is where you add that.

We provide this hook because we don't make it easy to change the instance methods - we try to discourage global namespace use - so this is the only way to add the data.

hooks

This goes along the lines of requiredData; if you have any functions that the instance needs to have, just add them to this Object hash and they will be given dot notational access:

var User = RestfulModel.generate({
  className: 'User',
  fields: ['firstName', 'lastName'],
  hooks: {
    fullName: function(){return (this.firstName + ' ' + this.lastName);}
  }
});

var user = User.new({firstName: 'Michael', lastName: 'Christenson II'});
user.fullName; // Michael Christenson II

Next Up

It's time to start learning how to use a model and it's instances.