Reputation: 3333
My 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
In posts_controller.rb
, I would like to do:
def create
broadcast("/posts/new") do
$('.user-win .posts').prepend('j(render('/posts/broadcast'))'));"
end
end
But obviously it gives an error:
ArgumentError (wrong number of arguments (0 for 1))
app/controllers/application_controller.rb:21:in `broadcast'
Any ideas?
Upvotes: 0
Views: 382
Reputation: 2810
You can not write JavaScript inside a controller action all you can do is to render a JavaScript template after the post has been successfully created and then inside your create.js.erb
file call the broadcast method.
#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
Now make a 'create.js.erb' file inside app/controllers/posts/
with the following code
#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 %>
Now create a _post.html.erb
file inside 'app/controllers/posts/' and write the html that you want to broadcast and render inside view
Upvotes: 2