Rails method as a nested resource
I'm wondering about the clever way to do this...
I have methods that return a value when passed an an obj开发者_如何转开发ect as parameter, such as:
I'd like to use the exact same methods as a nested resource to call via jQuery/Ajax, like so:
.load('/location/8/average_rainfall')
I understand how to define the route, but how do I tell my method to 'find' /location/8 and use that as it's parameter instead of @location as expected?
Thanks!
Not sure what your exact situation is, but one option would be to use a data-prefix attribute (html5). You can then grab the URL from that with javascript.
So if on a div:
<div data-rainfall_path="<%= average_rainfall_path(@location) -%>"></div>
Then just grab it with jQuery to make your ajax request.
That is the clever way I would do it.
It seems like you're trying to use view helpers and controller logic where a model would be ideal. You should stick the average_rainfall method in your Location model, then use that in the view like so:
<%= @location.average_rainfall %>
Then in your Locations controller use it by calling /locations/1/avg_rainfall
from the javascript.
def avg_rainfall
@location = Location.find( params[:id] )
render :json => { :avg_rainfall => @location.average_rainfall }
end
I just pass URLs into JavaScript when generating the view, something like this:
var ajaxWidget = new AjaxWidget('<%= average_rainfall(@location) %>');
This works for me because I don't need to pass heaps of URLs around. I just pass the base URL into the object and then append action names in JavaScript as necessary to make my Ajax calls. The problem with this is that I can't keep JavaScript completely unobtrusive, so I'd like to see a better answer.
精彩评论