我想用新的消息替换所有消息,并再次将计时器设置为关闭。但脚本index.js.erb不呈现消息。
我做了以下事情:
polling.coffee:
window.Poll = ->
setTimeout ->
$.get('/messages')
, 5000
jQuery ->
Poll() if $('#messages').size() > 0
index.js.erb的
$('#messages').find('.media-list').html('#{<%= escape_javascript(render(
:partial => @messages,
:layout => false
))%>}');
window.Poll();
我在application.js
中添加了// = require pollingnew.html.haml
- if current_user
.panel.panel-default#messages
.panel-body
%ul.media-list
= render @messages
.page-header
%h1 Join the discussion!
= render "form"
- else
visit root_path
escape_javascript有什么问题(渲染....?如何正确传递给HAML?
更多代码:
class MessagesController < ApplicationController
before_action :authenticate_user!
def index
@messages = Message.order('created_at ASC')
end
def new
@message = Message.new
@messages = Message.order('created_at ASC')
end
def create
respond_to do |format|
@message = current_user.messages.build(message_params)
if @message.save
flash[:success] = 'Your message was successfully posted!'
else
flash[:error] = 'Your message cannot be post!'
end
format.html{ redirect_to root_path }
format.js
end
end
private
def message_params
params.require(:message).permit(:body)
end
end