self-joinbatman.js

Self joins in Batmanjs


How can I implement the self-joins in Batmanjs?

In rails, as found here, it goes like this:

class Employee < ActiveRecord::Base
  has_many :subordinates, class_name: "Employee", foreign_key: "manager_id"
  belongs_to :manager, class_name: "Employee"
end

My current Batmanjs equivalent model looks like this:

class Employee extends Batman.Model
  @resourceName: 'employees'
  @storageKey: 'employees'

  @persist Batman.LocalStorage

  @has_many 'subordinates', name: "Employees", foreignKey: "manager_id"
  @belongs_to 'manager', name: "Employee"

Solution

  • I think that should work, if you just switch:

    Also, you may have to add an encoder for id with the LocalStorage adapter. LocalStorage converts the value to a string, but batman.js expects an integer, so you have to coerce it back to integer in the encoder.

    Here's an example of self-joins (you can copy-paste the encoder from there, too):

    http://jsbin.com/cukapedo/18/edit

    Pasted here for posterity:

    class App.Color extends Batman.Model 
      @resourceName: 'color'
      @persist Batman.LocalStorage
      @encode 'name', 'source_color_id'
      # required for numbers in localStorage:
      @encode 'id', 
        encode: (val) -> +val
        decode: (val) -> +val
    
      @hasMany 'child_colors', name: 'Color', foreignKey: 'source_color_id'
      @belongsTo 'source_color', name: 'Color'