4

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') %>");
Jack Daniel
  • 2,397
  • 8
  • 33
  • 58

4 Answers4

8

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) %>");
Community
  • 1
  • 1
Dabrorius
  • 1,039
  • 1
  • 8
  • 17
  • yes, it's working, but I have another problem with showing comment after saving. the thread in here: http://stackoverflow.com/questions/29240931/rails-4-ajax-comments-are-not-showing – Jack Daniel Mar 25 '15 at 16:56
3

Please try this code.

window.location.href = "<%= recipe_path(@recipe) %>"
ROR
  • 441
  • 2
  • 13
2

So if I understood well, you want to redirect to the recipe show page after adding the comment so you can update the page with the new comment? If so you can do that without redirecting, you can just append the newly created comment to the recipe comments.

add_new_comment.js.erb

$('#comments').append("<%= j (render @comment) %>");

If you really want to redirect use:

window.location.assign('your_url');
mtkcs
  • 1,696
  • 14
  • 27
0

Try rendering JS with:

render :js => "window.location = '/recipes/#{@recipe.id}'"

Hope it helps :)