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

本文关键字:js format 新方法 page 没有 使用 Rails respond to      更新时间:2023-09-26

我正在尝试将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文件。它们以类似的方式工作,允许访问实例变量和助手方法。