问题
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?
回答1:
Your messages.js.erb
is in assets
folder and ERB will run only once at assets compilation time.
Easier is to format before broadcasting while still in ruby controller context:
ActionCable.server.broadcast 'messages',
body: helpers.simple_format(@message.body),
user: @message.user.username,
time: @message.created_at
回答2:
When you have Ruby code that you want to run inside any of your .erb files, you must use the <% ... %>
or <%= ... %>
notation surrounding the Ruby text. The =
in <%= ... %>
is for outputting the code.
https://guides.rubyonrails.org/layouts_and_rendering.html
回答3:
If you want data
to be present here, it'll have to be an instance variable like @data
that's assigned in the controller in order to be present when the view gets rendered.
From there you can do anything you want in "Ruby mode" engaged using:
render_message: function(data) {
return "<div class='message'><div><strong><%= @data.user %>:</strong> <%= simple_format(@data.body) %></div><div class='date'><%= readable_datetime(@data.time) %></div></div>"
}
Or something approximately like that.
Remember that ERB substitutions are applied once and only once before the content is forwarded to the client for processing. There's no way to run Ruby after the output is rendered.
来源:https://stackoverflow.com/questions/54583221/how-to-use-ruby-in-a-js-assets-file-undefined-method-body