Skip to content

Much Ado About an Instance and a Model

m3talsmith edited this page Apr 6, 2013 · 7 revisions

Much Ado About an Instance

Once you have a Model, you need an instance right? Of course right! Let's take care of that for you :)

Let's start with a Model

var User = RestfulModel.generate({className: 'User', fields: ['name']});

Once we have the User Model we can use it to query for data on that model or create a new instance. As of tag 0.5, the queries supported are:

  • Model#all
  • Model#find (only by id right now)
User.all(); // Gets the baseUrl, parses the json, and returns an array of built instances of User

Full support for find, where, and scopes are forth coming.

Model#all can take an optional callback. Since this is done asynchronously, we highly recommend you use it that way.

User.all(function(data){
  console.log(data);
}); // Gets the baseUrl, parses the json, and runs the callback with an array of built instances of User

All of the query methods will support callbacks as development proceeds.

Instance Enters Stage Right

There are two methods you can use to create an instance: Model#build and Model#new. New is an alias for build.

var user = User.new({name: 'Charlie'});

Notice we are not using new User(). That's because User, as a Model, is actually an Object Literal.

In order to find a particular model use the find method:

var user1 = User.find('someid1'); // Finds a user via: GET /users/someid1

Find always returns a model, if it finds one, so you can use it easily with a callback like so:

function LogUser(model){
  console.log(model);
}

var user2 = User.find('user2', LogUser);
/*
  Finds a user via: GET /users/user2
  Calls callback and passes in the returned user
*/

Please, refer to our roadmap (upcoming (we should totally put that on the roadmap! (a roadmap for the roadmap!))) for all the planned features for instance and models.

Encore?

Well not yet, but thanks for asking. We'll keep this updated as soon as methods get added. When we're done, then you can flattr us or something ;)