2012-07-19 16 views
7

Estoy simplemente tratando de obtener mi archivo index.js.erb para ejecutar un comando de alerta ("hola"), sin embargo, no está funcionando. Soy bastante nuevo en los rieles, y me preguntaba si ustedes podrían ayudarme. Parece que el método de índice servers_controller.rb no está ejecutando format.js correctamente. ¿Alguna sugerencia/idea?Rails js.erb archivo no se está ejecutando

servers_controller.rb

def index 
    @servers = Server.all 

    update_all_servers #calls the method update_all_servers in application_controller.rb 

    respond_to do |format| 
     format.html # index.html.erb 
     format.json { render json: @servers } 
     format.js #index.js.erb 
    end 
end 

index.js.erb

alert("hi"); 
$("#comments").fadeOut(); 

index.html

<%- model_class = Server.new.class -%> 
<div class="page-header"> 
    <h1><%=t '.title', :default => model_class.model_name.human.pluralize %></h1> 
</div> 
<table class="table table-striped"> 
    <thead> 
    <tr> 
<!--  <th><%= model_class.human_attribute_name(:id) %></th> --> 
     <th><%= model_class.human_attribute_name(:hostname) %></th> 
     <th><%= model_class.human_attribute_name(:port) %></th> 
    <!-- <th><%= model_class.human_attribute_name(:username) %></th> 
     <th><%= model_class.human_attribute_name(:password) %></th> 
     <th><%= model_class.human_attribute_name(:ssh_username) %></th> 
     <th><%= model_class.human_attribute_name(:ssh_password) %></th> 
     <th><%= model_class.human_attribute_name(:source_branch) %></th> --> 
     <th><%= model_class.human_attribute_name(:source_revision) %></th> 
     <th><%= model_class.human_attribute_name(:release) %></th> 
     <th><%= model_class.human_attribute_name(:rhel_version) %></th> 
     <th><%= model_class.human_attribute_name(:gpu_type) %></th> 
     <th><%= model_class.human_attribute_name(:total_users) %></th> 
     <th><%= model_class.human_attribute_name(:current_users) %></th> 
     <th><%= model_class.human_attribute_name(:created_at) %></th> 
     <th><%=t '.actions', :default => t("helpers.actions") %></th> 
    </tr> 
    </thead> 
    <tbody> 
    <% @servers.each do |server| %> 
     <tr> 
    <!--  <td><%= link_to server.id, server_path(server) %></td> --> 
     <td><%= server.hostname %></td> 
     <td><%= server.port %></td> 
    <!--  <td><%= server.username %></td> 
     <td><%= server.password %></td> 
     <td><%= server.ssh_username %></td> 
     <td><%= server.ssh_password %></td> 
     <td><%= server.source_branch %></td> --> 
     <td><%= server.source_revision %></td> 
     <td><%= server.release %></td> 
     <td id="comments"><%= server.rhel_version %></td> 
     <td><%= server.gpu_type %></td> 
     <td><%= server.total_users %></td> 
     <td><%= server.current_users %></td> 
     <td><%=l server.created_at %></td> 
     <td> 
      <%= link_to t('.edit', :default => t("helpers.links.edit")), 
         edit_server_path(server), :class => 'btn btn-mini' %> 
      <%= link_to t('.destroy', :default => t("helpers.links.destroy")), 
         server_path(server), 
         :method => :delete, 
         :confirm => t('.confirm', :default => t("helpers.links.confirm", :default => 'Are you sure?')), 
         :class => 'btn btn-mini btn-danger' %> 
     </td> 
     </tr> 
    <% end %> 
    </tbody> 
</table> 

<%= link_to t('.new', :default => t("helpers.links.new")), 
      new_server_path, 
      :class => 'btn btn-primary' %> 

application.js

// This is a manifest file that'll be compiled into application.js, which will include all the files 
// listed below. 
// 
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, 
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. 
// 
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the 
// the compiled file. 
// 
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD 
// GO AFTER THE REQUIRES BELOW. 
// 
//= require jquery 
//= require jquery_ujs 
//= require twitter/bootstrap 
//= require_tree . 
+0

¿Se ejecuta el javascript si elimina la segunda línea? Intente solo ejecutar la alerta por sí mismo. – cdesrosiers

+0

quitar la segunda línea aún no funciona :( – Rahul

+0

¿Y está seguro de que la acción del índice se está llamando? – cdesrosiers

Respuesta

2

punto de su navegador para /servers.js y se mostrará el js, pero no va a funcionar, ya que no está en una etiqueta de script.

La sección respond_to elige uno y solo un tipo de medio para responder, por lo que cuando está buscando una página html, si desea incluir algún javascript, debe estar en la página html en una etiqueta de script de alguna manera. El formato index.js.erb es para las solicitudes que se realizan únicamente para la salida de JavaScript, como las solicitudes ajax.

+0

¡Gracias, intentaré esto! – Rahul

+0

Entonces, ¿tiene un archivo method.js para el método def que también incluya el código de ruby ​​<% %> en rieles 4? antes de que se requiera agregar .erb en la extensión – Rubytastic

1

Sé que esta pregunta es antigua, aunque en este caso es la solución, porque tropecé con este problema dos veces el día de hoy, sin siquiera recordar;)

Según this entrada del blog, usted debe comprobar su request type. Tiene que ser JS. Si está solicitando esa acción de controlador a través del AJAX, simplemente omita el dataType-attribute. Esto establecerá el tipo de solicitud como */*, pero seguirá funcionando.

Ejemplo:

$.ajax({ 
    url: '/users/auth/facebook/callback', 
    type: 'GET' 
}); 

EDITAR

La petición al controlador debería tener este aspecto:

Processing by Users::OmniauthCallbacksController#facebook as JS 

Con mi solución que se verá así:

Processing by Users::OmniauthCallbacksController#facebook as */* 

Establecer el tipo de datos en 'JS' no funcionó para mí, pero seguirá funcionando como si fuera un JS.

Cuestiones relacionadas