我的application_controller.rb
:
class ApplicationController < ActionController::Base
def broadcast(channel, &block)
message = {:channel => channel, :data => capture(&block)}
uri = URI.parse("http://localhost:9292/faye")
Net::HTTP.post_form(uri, :message => message.to_json)
end
end
在posts_controller.rb
中,我想这样做:
def create
broadcast("/posts/new") do
$('.user-win .posts').prepend('j(render('/posts/broadcast'))'));"
end
end
但很明显它会出错:
ArgumentError (wrong number of arguments (0 for 1))
app/controllers/application_controller.rb:21:in `broadcast'
有什么想法吗?
答案 0 :(得分:2)
您无法在控制器操作中编写JavaScript,您只能在成功创建帖子后呈现JavaScript模板,然后在create.js.erb
文件中调用广播方法。
#posts_controller.rb
def create
@post = Post.new(post_params)
respond_to do |format|
if @post.save
format.js {render :status => :ok}
else
format.js {render :status => :unprocessable_entity}
end
end
end
现在制作一个&#39; create.js.erb&#39; app/controllers/posts/
内的文件,包含以下代码
#create.js.erb
<% if @post.errors.any? %>
# render error
<% else %>
# broadcast the newly created post to "/posts/new" channel
<% broadcast("/posts/new") do %>
$('.user-win .posts').prepend('<%=j render @post %>');
<% end %>
<% end %>
现在在app / controllers / posts /&#39;内创建一个_post.html.erb
文件。并编写您要广播的html并在视图中呈现