Rails:使用控制器呈现js.erb模板

cho*_*bin 2 ajax ruby-on-rails

我有一个rails应用程序尝试合并一些AJAX,其中单击新打开一个模态窗口和一个窗体.我希望能够显示验证错误,如果失败,那么在我的创建操作中,我想重新渲染new.js.erb文件.这是正确的方法吗?

def create
    @place = Place.new(params[:place])
    if @place.save
       redirect_to places_path, :notice => "Successfully created place"
    else
       render "new.js.erb"
    end
end
Run Code Online (Sandbox Code Playgroud)

我得到的结果是在我的浏览器中转义js文本,如:

$("#new_grouping").html("<div class=\"modal-header\">\n  <a class=\"close\" data-   dismiss=\"modal\">×<\/a>\n  <h3>Create a new menu section<\/h3>\n<\/div>\n<form accept-charset=\"UTF-8\" action=\"/places/1-mama-s-pizza/groupings\" class=\"simple_form new_grouping\" id=\"new_grouping\" method=\"post\" novalidate=\"novalidate\">
Run Code Online (Sandbox Code Playgroud)

我已经尝试将各种选项放入渲染块但没有运气.有小费吗?

Vap*_*ire 15

最佳做法是支持AJAX和非AJAX调用,以防用户因任何原因关闭了javascript.

def create
  @place = Place.new(params[:place])

  respond_to do |format|
    if @place.save
      format.html { redirect_to places_path, :notice => "Successfully created place" }
      format.js   # renders create.js.erb, which could be used to redirect via javascript
    else
      format.html { render :action => 'new' }
      format.js { render :action => 'new' }
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

render :action => 'new'实际呈现控制器动作的模板new,其结果new.html.erb分别new.js.erb取决于它是否是一个非AJAX或AJAX调用.

new.js.erb你的ERB/javascript代码中:

$("#new_grouping").html("<%= escape_javascript(...) %>">
Run Code Online (Sandbox Code Playgroud)