Rails Sync - Update a counter in layout

235 views Asked by At

I am trying to show a counter of comments in the header of my site with several options:

ul
    = sync_new partial: "show", resource: Commontator::Comment.new
/ also with
ul
    = sync partial: "show", resource: Commontator::Comment.new
/ also with
ul
    = sync_new partial: "show", collection: Commontator::Comment.all
/ also with
ul
    = sync partial: "show", collection: Commontator::Comment.all

On my partial:

li
    a = comment.class.all.size

I am not clear about the differences between sync_new and sync.

What I understand:

  1. when passing collection, sync renders the partial for each item in the collection, this does not make sense to show a counter.
  2. when passing a resource, sync renders the partial for the passed resource, the problem is that when another comment is created or destroyed, passing resource won't update the counter.

Maybe I should go in a totally different direction, like using Faye directly. Any advice is appreciated.

Also posted here.

2

There are 2 answers

0
sites On BEST ANSWER

I will create a counter cache so when a new comment is posted the cache changes. I will render the model with the cache using:

= sync partial: 'discussion', resource: discussion

Then, when a comment is created, edited, deleted, partial should update. This will be the partial:

li
  ul
    - discussion.thread.comments.each do |comment|
      li = comment.body
0
Jay-Ar Polidario On

You can make use of Sync's Javascript Callbacks, such as beforeInsert, afterInsert, beforeUpdate, afterUpdate, beforeDestroy, and afterDestroy (more info).

You can use them to increase/decrease the counter displayed on a specific element whenever a comment has been inserted or removed:

class Sync.CommentShow extends Sync.View

  # OVERRIDE
  afterInsert: ->
    commentsCount += 1;
    $('#counter-div').text(commentsCount);

  # OVERRIDE
  afterRemove: ->
    commentsCount -= 1;
    $('#counter-div').text(commentsCount);

I hope you and other viewers find this useful.