spine / spine-rails

Spine plugin for Rails
171 stars 38 forks source link

"Uncaught Unknown record" best practices #34

Closed semanticart closed 1 month ago

semanticart commented 12 years ago

Using the scaffold generators, I end up with a Show Controller that looks like this for my Post model:

class Show extends Spine.Controller
  events:
    'click [data-type=edit]': 'edit'
    'click [data-type=back]': 'back'

  constructor: ->
    super
    @active (params) ->
      @change(params.id)

  # ...

Everything works out of the box if you hit the index and then click through to a post. However, if you visit a post and then refresh the page ( example url: http://localhost:3000/posts#/posts/3 ) it results in the "Uncaught Unknown record" error because the Show change function is called before the record has been fetched.

After some googling I came up with the following work-around for the constructor:

  constructor: ->
    super
    @active (params) ->
      if Post.count() > 0
        @change(params.id)
      else
        Post.fetch()
        Post.bind 'refresh', => @change(params.id)

It works but it feels terribly hacky and would have to also be implemented for the edit action as well.

So the question is, what's the best practice for dealing with this? I could drop the Spine.Route.setup() and just navigate to the index, but that doesn't really feel idea either.

Finally, if there is a best practice for dealing with this, should the scaffolding generator be updated to reflect that?

onlymejosh commented 11 years ago

Is there a solution to this?

semanticart commented 11 years ago

@onlymejosh I don't know the canonical answer but it seems like the preferred way to handle this is to bootstrap by embeding all the records in the DOM so that the records are always available. Note that this is directly at odds with the guide here http://spinejs.com/docs/ajax that advocates doing the fetch on page load

onlymejosh commented 11 years ago

@semanticart – Thanks. That does seem a little strange. If you load the records in the dom would be not be better to just load the full view using erb and than manipulate the results with spine? Doing it that way would make it unobtrusive which is one of my concerns.