Gerome John Pangan Gerome John Pangan - 1 year ago 279
Javascript Question

Rendering js.erb in rails

i want to try my js.erb if it is working?

here my view posts/index to trigger

<%= link_to "Like", {:controller => 'post', :id => post , :action =>'like'}, class: "btn btn-danger btn-xs", remote: true %>

my post controller

def like
@user = current_user
redirect_to posts_path
respond_to do |format|
format.html {redirect_to posts_path}
format.js { render :action => 'stablelike' }


and this is my js.erb to test


and this is my error: when i inspect my Chrome

AbstractController::DoubleRenderError at /post/like/85

Render and/or redirect were called multiple times in this action. Please note that you may only call render OR redirect, and at most once per action. Also note that neither redirect nor render terminate execution of the action, so if you want to exit an action after redirecting, you need to do something like "redirect_to(...) and return".

app/controllers/posts_controller.rb, line 83

``` ruby
78 @user = current_user
79 @post.liked_by(@user)
80 redirect_to posts_path
81 respond_to do |format|
82 format.html {redirect_to posts_path}

83 format.js { render :action => 'stablelike' }

85 end
86 end

Answer Source

In a controller action, neither render nor redirect_to stops the execution of the action. That is why you're getting a DoubleRenderError. Remove the first redirect_to and everything should be fine.

def like
  @user = current_user
  @post.liked_by(@user) # I am unsure what you're trying to accomplish here
  respond_to do |format|
    format.html { redirect_to posts_path }
    format.js { render :stablelike }

If this doesn't work, probably you have not setup stablelike action to respond to xhr requests. You can do that by

def stablelike
  respond_to  do |format|
    # other formats
    format.js # by default looks for `stablelike.js.erb`
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download