I started using Ruby on Rails today and love it.
The one thing I haven't been able to answer by myself is why the first
link below works and the second doesn't:
<%= link_to "Test Regular", { :action => "show", :id => "1" } %>
<%= link_to_remote "Test Ajax", :update => "listing", :url =>
{ :action => "show", :id => "1"} %>
I am trying to load the html at http://localhost:3000/listings/1 into
a div on my page with the id listing. That URL works when accessed
directly or via link_to. However, when I click on the "Test Ajax"
link then the following text loads in my listing div: "Unknown action:
No action responded to 1". What really puzzles me is that I even see
in FireBug that the when I click on the "Test Ajax" link that a
request is issued to the correct URL: http://localhost:3000/listings/1
The source generated by Rails is:
<a href="#" onclick="new Ajax.Updater('listing', '/listings/1',
{asynchronous:true, evalScripts:true, parameters:'authenticity_token='
+ encodeURIComponent('fda1badbcc7be1ff0d55829e684ecbe00579a97b')});
return false;">Test Ajax</a>
<a href="/listings/1">Test Regular</a>
I'm assuming you're using the basic scaffold code, which uses RESTful
routing, or are making an app with RESTful routes.
Without arguments, the AJAX call you are firing is sending a POST
request to the server to the URL /listings/1. As there is no RESTful
action/id which will respond to a POST of listings/1, your URL is
falling through the map.resources RESTful routing, and is ending up
caught by the default non-REST routes at the bottom of routes.rb which
is correctly(?) interpreting your /listings/1 as :controller =>
'listings', :action > '1'.
The secret to getting this to work is to include :method => :get in
your list of arguments to link_to_remote. That will send the AJAX
request as a GET, and allow the URL to be caught by the RESTful
map.resources method.
Incidentally, this stands for periodically_call_remote as it uses the
same syntax.
Ah, right because a POST will be meant for creates. That makes sense
now. I hadn't considered the link_to_remote request would be a POST
nor that a POST would cause problems.
Thanks so much for helping us noobs out Simon.
FYI, you can check out what sets of HTTP verbs and URL input will
trigger what controller/action by running 'rake routes' in your rails
app directory. If you get more routing 'huh?!' moments (and a
supposedly RESTful route falling through to the default non-REST
routes is a good example), then compare the output from rake routes to
what your development.log is telling you your browser is submitting.
You'll usually find the culprit there.