Rails 3.1:使用'respond_to .的新方法format.js& # 39;没有'page
Rails 3.1: The new way to use 'respond_to ... format.js' without the 'page' variable
我正在尝试将Ruby on Rails更新到版本3.1。我遵循了升级到Rails 3.1的屏幕视频,除了
语句外,所有这些似乎都可以工作。format.js { render(:update) { |page| page.redirect_to @article } }
在许多控制器中,我有如下代码:
def create
...
respond_to do |format|
format.js { render(:update) { |page| page.redirect_to @article } }
end
end
在上述所有情况下,当我尝试提交执行JS请求的相关表单时,我得到以下错误:
ActionView::MissingTemplate (Missing template articles/update, application/update with {:handlers=>[:erb, :builder, :coffee], :formats=>[:js, :html], :locale=>[:en, :en]}. Searched in:
* "/<MY_PROJECT_PATH>/app/views"
):
app/controllers/articles_controller.rb:114:in `create'
Rendered /<...>/.rvm/gems/ruby-1.9.2-p136/gems/actionpack-3.1.0/lib/action_dispatch/middleware/templates/rescues/missing_template.erb within rescues/layout (0.3ms)
我知道这个问题与RJS模板有关,因为它们在3.1版本中不再可用。因此,为了运行一些JavaScript代码,在我的控制器文件中,我可能'应该'可以插入一些JavaScript代码,如以下示例所示:
format.js { render :js => "alert('Hello Rails');" }
BTW:…,但, 是建议使用JavaScript代码直接在控制器文件?
考虑上述create
控制器动作中的代码,我想在成功提交后将用户重定向到@article
路径。我可以:
format.js { render :js => "window.location.replace('#{article_url(@article)}');" }
. .但是,我怎么能做同样的事情通过遵循"Ruby on Rails做事的方式"?RoR 3.1将如何处理这些情况?
我会选择:
render js: %(window.location.href='#{article_path @article}')
或者在你的application_controller.rb
中放置一些东西:
def js_redirect_to(path)
render js: %(window.location.href='#{path}') and return
end
然后在控制器中你可以调用:
js_redirect_to(article_path @article)
注意我只是编的,没有测试:)
不建议在控制器文件中直接使用javascript代码。
代替.rjs
,您可以使用.js.erb
文件。它们以类似的方式工作,允许访问实例变量和助手方法。
相关文章:
- 可以't让我的if语句处理js中的html表单输入
- 使用agility.js进行页面布局和合成
- 使用Clipboard.js复制span文本
- 使用JS如何动态更改显示的html文件中的文本背景颜色
- Rails 4 ActionController::UnknownFormat format.js error
- Rails Edge Guides,AJAX示例 - 为什么同时使用“format.js”和“format.json”
- 在format.html和format.js之间显示Rails3 Flash消息
- Rails 3.1:使用'respond_to .的新方法format.js& # 39;没有'page
- 为什么我的Rails控制器期望JSON从format.js调用
- Error: ActionController::Unknown Format (for format.js)
- base_url in a .JS format
- Moment.min.js这个.Format不是一个函数
- 我如何使用format.js返回错误消息并更新我的UI
- Node.js util.format() as String.prototype
- Rails: format.js将我重定向到一个空白页面
- Js-routes在url中添加(::format)
- Rails Form_Tag Ajax Format.js ActionController::未知格式
- Moment.js-Moment().format()创建无效日期
- 使用responsdto|format|format.js在一个模态中显示一条消息
- JavaScript: format and Unformat Number: Library numbro.js