I'm following this tutorial and having a problem where using ruby in an ActionCable file causes an undefined method 'body' error. How can I use ruby in this file? I want the data that's submitted over Action Cable to be properly formatted when it is appended, and I cannot do that with plain js. This is my app/assets/js/channels/messages.js.erb file:
App.messages = App.cable.subscriptions.create('MessagesChannel', {
received: function(data) {
$("#response").val("");
$('#messages').append(this.render_message(data));
$("#conversation-main").scrollTop($("#conversation-main")[0].scrollHeight);
},
render_message: function(data) {
return "<div class='message'><div><strong>" + data.user + ":</strong> <%= simple_format(@message.body) %></div><div class='date'><%= readable_datetime(@message.created_at) %></div></div>"
}
});
I can't do simple_format(data.body) since that variable is js. Here's the #create action in my messages controller:
def create
@message = @conversation.messages.new(message_params)
@message.user = current_user
respond_to do |format|
if @message.save
ActionCable.server.broadcast 'messages',
body: @message.body,
user: @message.user.username,
time: @message.created_at
head :ok
end
end
end
I have @message defined in the action, and it should be passed onto the js.erb file. But it's not. Why?
from how to use ruby in a js assets file? (undefined method 'body')
No comments:
Post a Comment