在Rails 3中如何处理js.erb文件

5
我正在将一个标准的脚手架生成的应用程序转换为使用AJAX和JQuery,方式与这篇文章中指定的方式类似:http://stjhimy.com/posts/07-creating-a-100-ajax-crud-using-rails-3-and-unobtrusive-javascript
我按照以下步骤操作:
  • 使用2个partials创建复合Index视图;
  • 更新控制器,只保留Index、Create、Edit、Update和Destroy操作;
  • 为Create、Edit、Update和Destroy操作创建js.erb文件,使用JQuery函数来更新DOM。
但是似乎无法访问js.erb文件。我把js.erb文件放在视图文件夹中,例如app/views/customers/create.js.erb
create.js.erb的代码如下:
<% if @customer.errors.any? -%> 

   /*Hide the Flash Notice div*/
   $("#flash_notice").hide(300);

   /*Update the html of the div customer_errors with the new one*/
   $("#customer_errors").html("<% @customer.errors.full_message.each do |msg| %>
                              <li><%= msg %></li>
                              <% end %>");

   /*Show the div customer_errors*/
   $("#cust0mer_errors").show(300);

<% else -%>

   /*Hide the div customer_errors*/
   $("#customer_errors").hide(300);

   /*Update the html of the div flash_notice with the new one */
   $("#flash_notice").html("<%= flash[:notice] %>");

   /*Show the flash_notice div*/
   $("#flash_notice").show(300);

   /*Clear the entire form*/
   $(":input:not(input[type=submit])").val("");

   /*Replace the html of the div posts_list with the updated new one*/
   $("#customers_list").html("<%= render "customers" %>";

   <% end %>

以下是表单的代码:
index.html.erb文件
<div id="customer_form"><%= render 'form' %></div>
<div id="customers_list"><%= render 'customers' %></div>
<%= form_for(@customer, :remote => true) do |f| %>


  <div id="customer_errors" style="display:none"></div>

  <div class="field">
    <%= f.label :firstname %>
    <%= f.text_field :firstname %>
    <%= f.label :lastname %>
    <%= f.text_field :lastname %>
  </div>
  <div class="field">
    <%= f.label :email %>
    <%= f.text_field :email %>
    <%= f.label :phone %>
    <%= f.text_field :phone %>
  </div>
  <div class="field">
    <%= f.label :password %>
    <%= f.text_field :password %>
    <%= f.label :address_id %>
    <%= f.text_field :address_id %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

_customers.html.erb局部文件的名称为:

<table>
  <tr>
    <th>Firstname</th>
    <th>Lastname</th>
    <th>Email</th>
    <th>Phone</th>
    <th>Password</th>
    <th>Address</th>
    <th></th>
    <th></th>
    <th></th>
  </tr>

<% @customers.each do |customer| %>
  <tr>
    <td><%= customer.firstname %></td>
    <td><%= customer.lastname %></td>
    <td><%= customer.email %></td>
    <td><%= customer.phone %></td>
    <td><%= customer.password %></td>
    <td><%= customer.address_id %></td>
    <td><%= link_to 'Edit', edit_customer_path(customer), :remote => true %></td>
    <td><%= link_to 'Destroy', customer, :remote => true, :confirm => 'Are you sure?', :method => :delete %></td>
  </tr>
<% end %>
</table>

编辑

客户控制器的最新版本:

class CustomersController < ApplicationController

  before_filter :load

  def load
    @customers = Customer.all
    @customer  = Customer.new
  end

  def index   
  end


  def create
    @customer = Customer.new(params[:customer])
    if @customer.save
      flash[:notice] = "Customer was successfully created."
      @customers = Customer.all
      respond_to do |format|
        format.js
      end 

    end
  end 

  def edit
    @customer = Customer.find(params[:id])
    respond_to do |format|
      format.js
    end
  end

  def update
    @customer = Customer.find(params[:id])
    if @customer.update_attributes(params[:customer])
      flash[:notice] = "Customer was successfully updated."
      @customers = Customer.all
      respond_to do |format|
        format.js
      end   
    end
  end  

  def destroy
    @customer = Customer.find(params[:id])
    @customer.destroy
    flash[:notice] = "Customer successfully destroyed"
    @customers = Customer.all
    respond_to do |format|
      format.js
    end
  end
end

最新版的布局模板在将Jquery.js文件替换为rails.js后,包含以下标签:
    <%= stylesheet_link_tag :all %>
      <%= javascript_include_tag 'http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js' %>
      <%= javascript_include_tag 'rails' %>
      <%= csrf_meta_tag %>

最新日志:

Started GET "/customers" for 127.0.0.1 at Wed Dec 14 21:16:14 +0000 2011
  Processing by CustomersController#index as HTML
  Customer Load (1.3ms)  SELECT "customers".* FROM "customers"
Rendered customers/_form.html.erb (14.1ms)
Rendered customers/_customers.html.erb (28.1ms)
Rendered customers/index.html.erb within layouts/application (47.6ms)
Completed 200 OK in 74ms (Views: 56.3ms | ActiveRecord: 1.3ms)


Started GET "/customers/13/edit" for 127.0.0.1 at Wed Dec 14 21:17:20 +0000 2011
  Processing by CustomersController#edit as JS
  Parameters: {"id"=>"13"}
  Customer Load (1.1ms)  SELECT "customers".* FROM "customers"
  Customer Load (0.5ms)  SELECT "customers".* FROM "customers" WHERE "customers"."id" = 13 LIMIT 1
Rendered customers/_form.html.erb (16.1ms)
Rendered customers/edit.js.erb (17.6ms)
Completed 200 OK in 43ms (Views: 27.6ms | ActiveRecord: 1.5ms)


Started GET "/customers/13/edit" for 127.0.0.1 at Wed Dec 14 21:17:31 +0000 2011
  Processing by CustomersController#edit as JS
  Parameters: {"id"=>"13"}
  Customer Load (1.0ms)  SELECT "customers".* FROM "customers"
  Customer Load (0.3ms)  SELECT "customers".* FROM "customers" WHERE "customers"."id" = 13 LIMIT 1
Rendered customers/_form.html.erb (25.9ms)
Rendered customers/edit.js.erb (28.8ms)
Completed 200 OK in 52ms (Views: 39.0ms | ActiveRecord: 1.3ms)


Started DELETE "/customers/18" for 127.0.0.1 at Wed Dec 14 21:18:31 +0000 2011
  Processing by CustomersController#destroy as JS
  Parameters: {"id"=>"18"}
  Customer Load (1.0ms)  SELECT "customers".* FROM "customers"
  Customer Load (0.4ms)  SELECT "customers".* FROM "customers" WHERE "customers"."id" = 18 LIMIT 1
  AREL (0.4ms)  DELETE FROM "customers" WHERE "customers"."id" = 18
  Customer Load (0.7ms)  SELECT "customers".* FROM "customers"
Rendered customers/_customers.html.erb (120.3ms)
Rendered customers/destroy.js.erb (122.1ms)
Completed 200 OK in 198ms (Views: 134.1ms | ActiveRecord: 2.5ms)


Started GET "/customers" for 127.0.0.1 at Wed Dec 14 21:20:00 +0000 2011
  Processing by CustomersController#index as HTML
  Customer Load (1.6ms)  SELECT "customers".* FROM "customers"
Rendered customers/_form.html.erb (19.1ms)
Rendered customers/_customers.html.erb (23.8ms)
Rendered customers/index.html.erb within layouts/application (50.6ms)
Completed 200 OK in 76ms (Views: 54.9ms | ActiveRecord: 1.6m
1个回答

4
当您创建formlink_to对象时,需要确保它们具有:remote => true,否则路由将不会通过JS呈现操作。相反,它将使用默认的HTML进行呈现。
一个示例:
<%= form_for(@post, :remote => true) do |f| %>

或者

<%= link_to "Edit", edit_post_path(post), :remote => true %>

此外,请确保已安装最新版本的jQuery和jQuery Rails adapter:https://github.com/rails/jquery-ujs
另外需要注意的是,如果您在CRUD操作中使用100%的ajax,则不需要在上述代码中使用format.html,因为您只需要渲染JS文件(format.js)。
更新:我认为您可能有几个误解…您正在阅读的教程仅涉及将CRUD(创建、读取、更新、删除)操作转换为100%的ajax调用,这意味着它们是仅会以渲染.js.erb文件的方式响应的。所以当您检查页面是否为Processing SomeController#some_action as JS时,它仅适用于客户控制器内的createshowupdatedestroy操作。
要在Rails 3.0上安装jQuery和jQuery-UJS,请按照以下步骤操作:

请务必删除rails.js文件(如果存在),并使用复制到public目录的新jquery_ujs.js文件。如果提示,选择覆盖jquery_ujs.js。

然后运行rails generate jquery:install 更改您的布局模板如下:
<%= stylesheet_link_tag :all %>
<%= javascript_include_tag :defaults %>
<%= csrf_meta_tag %>

我必须说,这篇教程是我读过最差的教程之一。由于你似乎对Ruby on Rails非常新,所以我强烈建议阅读其他教程(如果您仍然想了解有关Rails中AJAX的内容,则可以阅读此处提供的教程:http://net.tutsplus.com/tutorials/javascript-ajax/using-unobtrusive-javascript-and-ajax-with-rails-3/,或者学习Rails本身更好的教程如此出色的教程:http://ruby.railstutorial.org/ruby-on-rails-tutorial-book)。

我已经放置了表单 - 你还需要什么? - JimmyBandit
你能否在提交表单或点击链接时发布服务器日志?此外,请检查浏览器控制台是否有任何JS错误。 - iwasrobbed
你的create控制器动作中仍然存在错误:@customers = customer.all 应该改为 @customers = Customer.all... 还有,在你的 create.js.erb 文件中也有另一个错误:$("#cust0mer_errors").show(300); 应该改为 $("#customer_errors").show(300); 你能否确认已安装jQuery和jQuery Rails适配器(https://github.com/rails/jquery-ujs)并删除了 format.html 的引用? - iwasrobbed
我一直询问jQuery的原因是因为您的Rails服务器日志显示“Processing by CustomersController#create as HTML”(format.html),但如果JS调用正确(通过jQuery),则应该是“Processing by CustomersController#create as JS” (format.js)。 - iwasrobbed
我已经进行了更改并从github网站安装了jquery。我修改了Gemfile并运行了bundle install,然后输入rails generate jquery --ui。这似乎很好用,但是我遇到了一个错误 - “路由错误缺少rails.js fire”。我将jquery.js重命名为rails.js,该错误消失了。我仍然有问题 - 编辑操作似乎仍会导致HTML处理请求,而销毁操作似乎会寻找show操作。我在下面包含了日志以及控制器中的最新代码。 - JimmyBandit
显示剩余18条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接