Faye + Rails +在控制器中发送消息

时间:2014-06-17 20:00:31

标签: ruby-on-rails sockets faye

我的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'

有什么想法吗?

1 个答案:

答案 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并在视图中呈现