Rails:使用控制器渲染js.erb模板 [英] Rails: rendering the js.erb template using the controller

查看:171
本文介绍了Rails:使用控制器渲染js.erb模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Rails应用,试图结合一些AJAX,在其中单击new会打开一个模式窗口和一个表单.我希望能够显示验证错误(如果失败),因此在我的create动作中,我考虑过重新呈现new.js.erb文件.这是正确的方法吗?

I have a rails app trying to incorporate some AJAX where clicking new opens a modal window and a form. I want to be able to display the validation errors if it fails so in my create action, i thought about re-rendering the new.js.erb file. Is this the right approach?

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

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

The result I get is escaped js text in my browser like:

$("#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\">

我尝试将各种选项放入渲染块,但是没有运气.有提示吗?

I've tried putting various options into the render block but no luck. Any tips?

推荐答案

最好的方法是同时支持AJAX和Non-AJAX调用,以防用户出于任何原因关闭了javascript.

The best practice would be to support both, AJAX and Non-AJAX calls, in case the user has javascript turned off for any reason.

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

render :action => 'new'实际上是将控制器操作new的模板呈现出来,该模板的结果分别为new.html.erbnew.js.erb,具体取决于它是非AJAX还是AJAX调用.

The render :action => 'new' actually renders the template of the controller action new which results to new.html.erb respectively to new.js.erb depending if it's a non-AJAX or an AJAX call.

new.js.erb中输入您的ERB/javascript代码:

In new.js.erb goes your ERB/javascript code:

$("#new_grouping").html("<%= escape_javascript(...) %>">

这篇关于Rails:使用控制器渲染js.erb模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆