我目前正致力于将用户头像添加到ActionCable聊天室帖子。在更改咖啡脚本代码以支持 user.user_profile.avatar.profile_thumb 扩展方法后,我在获取插入消息方面取得了一些进展。问题是,当化身不存在时,我在视图中收到“未定义”。我已经在_message.html.erb模板中有一个条件语句。如果不存在,那么应该用占位符图像替换用户头像。如何更改我的代码以正确插入占位符img或avatar(如果可用)?我正在使用Carrierwave作为图像。
_message.html.erb
<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>
chatrooms.coffee
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'><img class='d-flex align-self-start mr-3 purple-rounded rounded' src='http://via.placeholder.com/30x30'>#{data.profile_thumb}<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}
答案 0 :(得分:0)
当您向动作电缆广播时,您可以发送生成的字符串。使用rails,您可以生成一个html布局作为字符串(布局中的所有ruby代码都将被执行),然后将其与您的数据一起发送。
html = render_to_string(partial: 'messages/messages_drop_in', formats: :html, layout: false, locals: {YOUR NEEDED LOCALS})
播出后。在你的咖啡中:
active_chatroom.append(data.html)
参考文献
http://api.rubyonrails.org/v5.1/classes/AbstractController/Rendering.html http://guides.rubyonrails.org/action_cable_overview.html
希望这会有所帮助!