Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4: Redirect to another action with js

in my app I have show action with show.html.erb page, where I show the recipe and the comment for this recipe. and I wand add the ajax functionality to comment adding. in controller RecipeController I have add_new_comment action. can I from add_new_action redirect to show action from format.js?

show action:

def show
  @category = Category.where(id: @recipe.category_id).take
  @comments = @recipe.comments.recent.all.paginate(page: params[:page], per_page:15)
end

add_new_comment action:

def add_new_comment
  @recipe = Recipe.find(params[:recipe_id])
  if params[:comment].present?
    @comment = @recipe.comments.build
    @comment.comment = params[:comment]
    @comment.user = current_user
    respond_to do |format|
      if @comment.save
        format.html {redirect_to recipe_path(@recipe)}
        format.js {render action: 'show', :id => @recipe.id}
      end
    end
  end
end

and I have add_new_comment.js.erb

$('#comments').html("<%= j (render 'comments') %>");
like image 972
Jack Daniel Avatar asked Nov 05 '25 21:11

Jack Daniel


1 Answers

You can use window.location.replace, or window.location.href as described here

Just add the line to your add_new_comment.js.erb and it should work.

$('#comments').html("<%= j (render 'comments') %>");
window.location.replace("<%= recipe_path(@recipe) %>");
like image 67
Dabrorius Avatar answered Nov 07 '25 14:11

Dabrorius



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!