Burak Özmen
Burak Özmen

Reputation: 873

Rendering an object passed through Pusher in Rails

I am trying to implement a realtime chat application.

I'm using pusher to notify server about the button click, and then pass the message object as message to a subscriber. What I need to do is, render that message in other user's chat screen(show.html.erb) dynamically. Here is my cycle:

// MessagesController.rb

    def create
        conversation = Conversation.find(params[:conversation_id])
    message = Message.create(content: params[:content], user_id: params[:user_id])
    conversation.messages << message
        Pusher['test_channel'].trigger('my_event', {
      message: message
    })
    end

And my subscriber is

// show.html.erb    
    // some html code 
       <ul class="chats">
       <%= render @messages %>
       </ul>
    // some html code

    <script>
         // some js code
         var channel = pusher.subscribe('some_channel');

         channel.bind('some_event', function(data) {
             // What to do here?
         });
    </script>

Upvotes: 0

Views: 218

Answers (2)

DickieBoy
DickieBoy

Reputation: 4956

This assumes you are using jquery. It's also untested so may have a few bugs/syntax errors.

Ajax method:

JS

channel.bind('some_event', function(data) {
  $.ajax({
    url:'/messages/'+data.message.id,
    success:function(html){ $('.chats').append(html)}
  });
});

routes:

match '/messages/:id' => "messages#show_no_layout"

controller:

def show_no_layout
  @message = Message.find(params[:id])
  render "show", layout: false
end

view(show.html.erb):

<%= *whatever you want in here* %>

ICH(read more) method:

This will of course require adding an extra js file which is why its not my first suggestion.

Template:

<script id = "messageTemplate" type = "text/html">
   {{ message.content }}
   // plus whatever else you want.
</script>

channel.bind('some_event', function(data) {
  messageHtml = ich.messageTemplate(data.message);
  $('.chats').append(messageHtml);
});

Upvotes: 1

B Seven
B Seven

Reputation: 45941

If you are using JQuery,

channel.bind('some_event', function(data) {
    $('.message').text(data.message);
});

See this tutorial.

Upvotes: 0

Related Questions