0

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"
Raymundus
  • 2,173
  • 1
  • 20
  • 35

1 Answers1

1

I think that should work, if you just switch:

  • has_many/belongs_to => hasMany/belongsTo
  • name: "Employees" => name: "Employee".

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'
rmosolgo
  • 1,854
  • 1
  • 18
  • 23
  • That works, thanks. My problem is probably in the testing: in the setup function the command red.get('child_colors') returns undefined. – Raymundus Jun 30 '14 at 19:57
  • Oh, I can't believe I missed it -- are you using `hasMany` and `belongsTo`, not `has_many`/`belongs_to`? (Also adding this to the answer) – rmosolgo Jun 30 '14 at 22:11
  • Yup, my fault sorry, i had it changed already. Everything works fine, except for when I'm calling the commands from the setup function in a Batman.TestCase. – Raymundus Jul 01 '14 at 06:03
  • I think it looks up associations against `Batman.currentApp`, which isn't defined until you call `MyApp.run()`. In your test setup, either call `MyApp.run()` or assign `Batman.currentApp = MyApp` yourself. Does that work?? – rmosolgo Jul 01 '14 at 23:12
  • Glad to hear it -- the next version of Batman.js will provide this information by itself :) https://github.com/batmanjs/batman/pull/1072 – rmosolgo Jul 02 '14 at 15:03