Rails jQuery适配器渲染三次

时间:2013-01-18 21:02:37

标签: ruby-on-rails ruby

我正在关注来自Apress 2010的Beginning Rails 3,更新的书。我遇到的问题是使用jQuery适配器使用Ajax动态加载模板。一切正常,但它似乎在页面上呈现三次。

以下是当用户点击“新评论”链接时动态加载它的方式。

视图/物品/ show.html.erb

<%= link_to "new comment",
            new_article_comment_path(@article, :format => :js),
            :remote => true,
            :id => 'new_comment_link' %>

然后我就这样渲染它。

视图/评论/ new.js.erb

$("<%= escape_javascript render :file => 'comments/new'," +
  " :formats => [:html], :handlers => [:erb] %>")
  .insertAfter('#comments');

然后我在日志中看到了这一点。

Started GET "/articles/1/comments/new.js" for 127.0.0.1 at 2013-01-18 14:51:05 -0600
Processing by CommentsController#new as JS
  Parameters: {"article_id"=>"1"}
  Article Load (0.2ms)  SELECT "articles".* FROM "articles" WHERE "articles"."id" = ? LIMIT 1  [["id", "1"]]
  Rendered comments/new.html.erb (53.8ms)
  Rendered comments/new.js.erb (54.6ms)
Completed 200 OK in 57ms (Views: 55.9ms | ActiveRecord: 0.2ms)

注意它呈现我的erb和js文件?不知何故最终会在我的页面上出现三次。

有关如何解决此问题的任何线索?我正在使用Rails 3.2.9,rails.js(最新)和jquery-1.9.0。

谢谢!

1 个答案:

答案 0 :(得分:0)

解决了!

原来我正在添加rails.js和jquery.js TWICE!

以下是skinny:assets / javascripts / application.js对于将javascript文件包含到您的应用中至关重要。基本上无论定义什么,都会被推送到页面。您只需要确保它在应用程序中至少定义一次。

视图/布局/ application.html.erb

<%= javascript_include_tag "application" %>

就是这样! Ajax jQuery适配器应该可以工作。不想在javascript文件夹中添加任何其他文件,因为这些文件也会被推出,而这正是你不想要的。基本上我是通过application.html.erb定义适配器并通过下载两个文件手动定义。希望这将有助于一路上某个失落的贫穷灵魂。

快乐黑客。

相关问题