Rails 3.0 / 3.1, jQuery & Ajax best practices

There are several questions related to the title on this post. The general theme of this post can be summarized as follows: "What am I missing / How do you do it better?"

Using the usual Googling / screencasts / API methods, I just finished learning basic knowledge about how to use the Rails 3.0-JQuery-Ajax command.

I remain with some (possibly significant?) Questions. In Railscast 242, Ryan ends the last update on the page with the following:

$("#products").html("<%= escape_javascript(render("products")) %>");

At first it seemed super weird, and still seems a bit strange: does the index.js.erb template know that there is a div ## products on the index.html page and the index.js.erb template itself is a problem with the update command? It seems to me that this is a small violation of the Separation of Concerns - shouldn't JS on the index.html page be the one that actually refreshes the page with the data that it receives from the post, unlike the script from the server that actually refreshes the page? Also, it seems a little fragile. For some stupid reason, if I rename the div to index.html to say "#products_collection" and forget to change index.js.erb, my index.html page will still work, but my Ajax update will not. I would like to know if you think the above points are valid / what to do with them, if any.

, : , , index.js index.html. , / . , , div. . ...

Ajax: , Ajax get, Ajax. , create.js.erb :

create.js.erb?

$("#products").prepend("<%=escape_javascript( render 'product_as_table_row', :product => @product))%>");

, . ... , :

create.js.erb?

<% flash.each do |key, value| %>
  $("div#flash").html("<div class='<%=key%>'><%=value%></div>");
<% end %>
$('div#flash div').fadeOut(10000);

$("#products").prepend("<%=escape_javascript( render 'product_as_table_row', :product => @product))%>");

, , , -- , - js. , - ? ? , create.js update.js ? 3.1? , Ajax , ?

? create.js.erb?

create.js.erb

<% if @thought.new_record? %>
  <%# ??? Throw in Validation-Error Form Updates? Display a Modal Dialog? %>
<% else %>
  $("#products").prepend("<%=escape_javascript( render 'product_as_table_row', :product => @product))%>");
<% end %>

, , , , Ajax DRY-ly , , . , , , . JS , . Ajax Rails 2.x, . ... , Rails, -. ? , .

+5
2

rails_ujs, : rails- 2----

+1

application.js,

update_product("<%= escape_javascript(render("products")) %>");

add_product("<%=escape_javascript(render 'product_as_table_row', :product => @product))%>");

etc..

-

+2

All Articles