Rails 4:使用js重定向到另一个动作

Jac*_*iel 3 ajax ruby-on-rails ruby-on-rails-4

在我的应用程序中,我使用show.html.erb页面显示操作,在这里我显示了该配方的配方和注释.我添加了ajax功能来添加注释.在控制器RecipeController我有add_new_comment动作.我可以从add_new_action重定向到显示format.js的操作吗?

显示行动:

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

add_new_comment动作:

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
Run Code Online (Sandbox Code Playgroud)

我有add_new_comment.js.erb

$('#comments').html("<%= j (render 'comments') %>");
Run Code Online (Sandbox Code Playgroud)

Dab*_*ius 6

您可以描述使用window.location.replace,或window.location.href 这里

只需将该行添加到add_new_comment.js.erb即可.

$('#comments').html("<%= j (render 'comments') %>");
window.location.replace("<%= recipe_path(@recipe) %>");
Run Code Online (Sandbox Code Playgroud)