Create a gist now

Instantly share code, notes, and snippets.

Embed
Supporting Rails Nested Resources in Batman.js
class App.Model extends Batman.Model
@persist App.Storage
@encodeAttributesFor: ->
@encodeAttributesForKeys ?= []
for key in arguments
if typeof key == 'string'
@encodeAttributesForKeys.splice(index,1) if (index = @encodeAttributesForKeys.indexOf(key)) > 0
@encodeAttributesForKeys.push key
class App.Storage extends Batman.RailsStorage
@::before 'create', 'update', (env, next) ->
if env.subject.constructor.encodeAttributesForKeys?
data = env.options.data
if namespace = @recordJsonNamespace(env.subject)
obj = data[namespace]
else
obj = data
for key in env.subject.constructor.encodeAttributesForKeys
if obj[key]
obj["#{key}_attributes"] = obj[key] if obj[key].length
delete obj[key]
next()
@::after 'update', @skipIfError (env, next) ->
if env.subject and env.subject.constructor.encodeAttributesForKeys?
for key in env.subject.constructor.encodeAttributesForKeys
objects = env.subject.get(key)
if objects?.constructor.name == 'AssociationSet'
objects.forEach (object) ->
if object.get('_destroy')
objects.remove(object)
else
object.get('dirtyKeys').clear()
object.get('_dirtiedKeys').clear()
class App.Store extends App.Model
@hasMany 'products'
@encodeAttributesFor 'products'
@orangewolf

This comment has been minimized.

Show comment
Hide comment
@orangewolf

orangewolf Dec 5, 2012

oooh, that's lovely.

oooh, that's lovely.

@redterror

This comment has been minimized.

Show comment
Hide comment
@redterror

redterror Dec 6, 2012

If there was a way to work this into the RailsStorage adapter then it seems like an easy merge. Not sure how you'd do that, but that seems like the right spot.

If there was a way to work this into the RailsStorage adapter then it seems like an easy merge. Not sure how you'd do that, but that seems like the right spot.

@kevinthompson

This comment has been minimized.

Show comment
Hide comment
@kevinthompson

kevinthompson Dec 13, 2012

Updated the implementation to use Batman.RailsStorage so that the toJSON method doesn't need to be overwritten.

Owner

kevinthompson commented Dec 13, 2012

Updated the implementation to use Batman.RailsStorage so that the toJSON method doesn't need to be overwritten.

@kevinthompson

This comment has been minimized.

Show comment
Hide comment
@kevinthompson

kevinthompson Jan 29, 2013

Added @::after 'update' callback to clean up nested objects after a successful updated.

Owner

kevinthompson commented Jan 29, 2013

Added @::after 'update' callback to clean up nested objects after a successful updated.

@turizoft

This comment has been minimized.

Show comment
Hide comment
@turizoft

turizoft Dec 18, 2013

Any chance of this getting merged into BatmanJS core?

Any chance of this getting merged into BatmanJS core?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment