Rails 3: Simple AJAXy Page updates?

Ed Jones picture Ed Jones · Oct 25, 2010 · Viewed 11.3k times · Source

I can't believe I've been looking four hours for this simple task, but I have.

In Rails 2.3, I could replace one section of a page with this simple code:

render :update do |page| page.replace_html "div_id", :partial => "new_content",... end

In Rails 3, Ryan Bates has me writing entire new javascript functions, switching from Prototype (rails default) to jQuery, and otherwise not enjoying life. The other tutes are no more straightforward.

What am I missing? How do we replace a <div> these days?

Answer

Ed Jones picture Ed Jones · Oct 26, 2010

Thanks, guys. The official answer seems to be that, yes, the team felt simple is the enemy of good and made it more complicated.

The first key is to create a .js.erb file NAMED for the method CALLING the ajax update. So if the index method handles the update, put the raw javascript in index.js.erb. This goes in the views folder.

Second, the code that worked in index.js.erb was

m = $('list_users');    
m.innerHTML = "<%= escape_javascript(render :partial => "reload_users") %>";

Then to make the call, add in the respond_to block of the controller method, add:

format.js

Finally, the calling view has:

<%= link_to "Update User List", @reload_users_path, :remote => true %>

By the way, supposedly all the old pages using page.replace will work if you install a plugin. The plugin download page suggests that it broke in the last releases of Rails 3 and has not been fixed. Also, various bloggers will come to your home and birch-switch you if you use it.