Model Relationship in “rails-backbone”

Introduction

Backbone-associations provides a way of specifying one to one and one to many relationships between Backbone models. Additionally, parent model instances (and objects extended from Backbone.Events) can listen in to CRUD events on any children – in the object graph – by providing an appropriately qualified even on deeply nested object graphs – and uses a low memory footprints.

Example:

Create a new rails application called Demo

  •      rails new Demo

Edit, /Gemfile.rb

  • gem ‘rails-backbone’

Install the gem and generate scaffolding by running following commands

  • bundle install
  • rails g backbone:install
  • rails g scaffold Job title:string description:string
  • rake db:migrate
  • rails g backbone:scaffold Job title:string description:string

Edit the jobs index view (app/views/jobs/index.html.erb)

     <div id=”jobs”></div>

     <script type=”text/javascript”>

            $(function() {

                 // Demo is the app name

                  window.router = new Demo.Routers.JobsRouter({jobs: <%= @jobs.to_json.html_safe -%>});

                   Backbone.history.start();

            });

</script>

Suppose in rails, we have a model relationship like,

class Job < ActiveRecord::Base
     belongs_to :user, :class_name => “User”, :foreign_key => “user_id”
end

class User < ActiveRecord::Base
has_many :jobs
end

To implement this relationship in backbone,

Edit the app/controller/jobs_controller.rb

class JobsController < ApplicationController
def index

@jobs = Job.all
respond_to do |format|

format.html # index.html.erb

format.json { render json: @jobs.to_json(:include=>[:user])}

end

end
end

Create a user model in backbone using below command which will create a new file as, app/assets/javascripts/backbone/models/user.js.coffee.

  • rails g backbone:model user name:string email:string

Then edit the same,

class Demo.Models.User extends Backbone.Model
paramRoot: ‘user’

defaults:
id: null
name: null
email: null

relations: [
{
type: Backbone.HasMany
key: ‘jobs’
relatedModel: ‘RailsBackboneRelational.Models.Job’
collectionType: ‘RailsBackboneRelational.Collections.JobsCollection’
includeInJSON: false
reverseRelation:
key: ‘user_id’,
includeInJSON: ‘id’
}
]

class Demo.Collections.UsersCollection extends Backbone.Collection
model: Demo.Models.User
url: ‘/users’

Again edit the file app/views/jobs/index.html.erb as mentioned below:

<div id=”jobs”></div>
<script type=”text/javascript”>
$(function() {
// Demo is the app name
window.router = new Demo.Routers.JobsRouter({jobs: <%= @jobs.to_json(:include=>[:user}).html_safe -%>});
Backbone.history.start();

});

Then edit the file app/assets/javascripts/backbone/models/job.js.coffee as mentioned below:

class Demo.Models.Job extends Backbone.Model
paramRoot: ‘job’
defaults:
id: null
user_id: null
title: null
description: null

relations: [
{
type: Backbone.BelongsTo
key: ‘user’
relatedModel: ‘RailsBackboneRelational.Models.User’
collectionType: ‘RailsBackboneRelational.Collections.UsersCollection’
includeInJSON: false
reverseRelation:
key: ‘user_id’,
includeInJSON: ‘id’
}
]

class Demo.Collections.JobsCollection extends Backbone.Collection
model: Demo.Models.Job
url: ‘/jobs’

Suppose you want to get the name of the Username associated with the Job, then add below mentioned file to the view in “app/assets/javascripts/backbone/templates/jobs/job.jst.ejs”

<td><%= title %></td>
<td><%= description %></td>
<td><%= user.name %></td>

<td><a href=”#/<%= id %>”>Show</td>
<td><a href=”#/<%= id %>/edit”>Edit</td>
<td><a href=”#/<%= id %>/destroy” class=”destroy”>Destroy</a></td>

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s