Skip to main content

How can I add an avatar using (Carrierwave) to the ActionCable Chatroom Project?

Rails • Asked by Darion Wood

The code that I have below is for the _message.html.erb partial

<div class="media">
  <% if message.user.user_profile.avatar.profile_thumb.present? %>
    <%= image_tag message.user.user_profile.avatar.profile_thumb, class: "d-flex align-self-start mr-3 img-thumbnail rounded" %>
  <% else %>
    <img class="d-flex align-self-start mr-3 purple-rounded rounded" src="http://via.placeholder.com/30x30">
  <% end %>
  <div class="media-body">
    <h5 class="mt-0">
      <%= message.user.username %>
    </h5> 
    <p>
      <%= message.body %>
    </p>
  </div>
</div>

The code below is from chatroom.coffee file.

App.chatrooms = App.cable.subscriptions.create "ChatroomsChannel",
  connected: ->
# Called when the subscription is ready for use on the server

  disconnected: ->
# Called when the subscription has been terminated by the server

  received: (data) ->
    active_chatroom = $("[data-behavior='messages'][data-chatroom-id='#{data.chatroom_id}']")
    if active_chatroom.length > 0

      if document.hidden
        if $(".strike").length == 0
          active_chatroom.append("<div class='strike'><span>Unread Messages</span></div>")

        if Notification.permission == "granted"
          new Notification(data.username, {body: data.body})

      else
        App.last_read.update(data.chatroom_id)

      # Insert the message
      active_chatroom.append("<div class='media'><div class='media-body'><h5 class='mt-0'>#{data.username}</h5> <p>#{data.body}</p></div></div>")

    else
      $("[data-behavior='chatroom-link'][data-chatroom-id='#{data.chatroom_id}']").css("font-weight", "bold")

  send_message: (chatroom_id, message) ->
    @perform "send_message", {chatroom_id: chatroom_id, body: message}

The message body and user name appends correctly. But, I have to refresh to see the user avatar or the placeholder image. It does not insert the entire partial view. I've been working hard to figure this out, and now I'm puzzled.

Care to help me out? Thanks


Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 22,346+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.