Ok, maybe this is a trivial topic, but as this was my first “real” AJAX experience in Rails 2.0, I spent some time solving this issue:
I wanted to sort a list of articles differently using AJAX. So in the appropriate action of the controller I added the format.js line:
respond_to do |format|
format.html # index.html.erb
format.js
format.xml { render :xml => @articles }
end
And then I created a new view template in the view folder belonging to that controller: index.js.erb.
This was my first fault! The correct file extension is .js.rjs! First this didn’t make sense to me, but I got some explanation here: http://www.railsforum.com/viewtopic.php?pid=47149
And then - in my index.js.rjs template - I wrote the following line:
page.replace_html :list, :partial => "list"
This replaces the HTML of the div list with a rendering of the partial _list.html.erb. I never had any doubt that this line was correct. ;-)
So far so good, but I got really ugly results clicking a link_to_remote link:
<%= link_to_remote 'Oldest Articles first', :update => 'list',
:url => { :action => "index", :sort_string => "created_at ASC" }, :method => :get %>
The result was something like:
try { Element.update ...
…followed by more strange ruby code, mixed with some of my list data in between, replacing the list-div. Here I expected the newly rendered, resorted list.
The problem was the :update => ‘list’ statement. That way, the code was not interpreted as JavaScript and got directly inserted into the div-tag. And as you can see, I specified to div to be updated in the page.replace_html call in index.js.rjs.
So, the correct call of link_to_remote would be without the :update parameter:
<%= link_to_remote 'Oldest Articles first', :url => { :action => "index",
:sort_string => "created_at ASC" }, :method => :get %>
Problem solved!
In short:
- the right file extension for responding to JavaScript is .js.rjs
- when using link_to_remote with page.replace_html don’t use the :update parameter
As I said above, this is not such a big problem when done correctly, but sometimes it’s an accumulation of 2 or 3 little issues that turn into a big one. At least for me.
Comments (1)
This Artikel finally stopped my headack and solved my stupid error. I had used linktoremote with :update in it. Thanks alot!!!
Posted by Jan Marsh | 14.08.08 10:02
Posted on 14.08.08 10:02