Thursday, April 20, 2017

Update Rails view with Faye from Database change (after_commit callback) on model

Leave a Comment

I am very puzzled and this is my first Faye or Pub/Sub implementation so please forgive me if this is a basic questions. I have not found answers anywhere else. Any help is appreciated.

How can I call and update a Rails view page from a model callback (after_commit, after_save etc)? I need a javascript code that does the view update to run from views/conferences/_show_current_participants.js.erb once the after_commit callback fires.

I have it setup and It Works to have the javascript execute and view update if I use a link_to tag with return => true on the view. The thing is I will Not have Any user interaction and need to push view updates to the page base solely on database changes (hence after_commit callback on model). Is this not the right tool/design pattern/approach?

I tried making an HTTP get request on the after_commit callback to http://localhost:3000/conferences/conference_id/_show_current_participants_url but that did not trigger Faye/the javascript to be executed on the page view.

Here it is: _show_current_participants.js.erb

<% participant_broadcast "/conferences/#{@conference.id}" do %>   alert('_show_current_participants.js.erb loaded');   $("#current_participants_js").html("<%= escape_javascript(render partial: 'conferences/show_current_participants.html', locals: { conference: @conference } ) %>"); <%end%> 

This works like a charm if I set it to trigger on a link_to tag with remote => true:

<li><%= link_to "Faye CALL", "#{@conference.id}/_show_current_participants", remote: true %></li> 

How can I modify this setup so instead of having to click on a link the Faye and subsequent partial's javascript gets activated on the after_commit model callback? Is this the wrong approach? How else can I tell my view to update based on a database change? Any help is appreciated. Thank you so very much to any kind soul willing to help me find the right direction.

Versions:

Faye 1.2.4 (not faye-rails)
Rails 4.1.5
Ruby 2.3.0
At this point more than a super pretty solution I am looking for something that works.

1 Answers

Answers 1

You should subscribe to messages with a javascript callback:

<script>    $(function() {        // Create a new client to connect to Faye        var client = new Faye.Client('http://localhost:3000/conferences');         // Subscribe to the public channel        var public_subscription = client.subscribe('/#{@conference.id}/_show_current_participants', function(data) {           $("#current_participants_js").html(data);         });    }); </script> 
If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment