Topic: OnClick/OnLoad + Ruby Function?

I don't know if this is just something really simple that is just flying over my head or what, but I couldn't seem to find any answers in all my RJS research. What I want to do is basically execute a simple ruby function on javascript onclick/onload events. So, an example might be:

(in view)

<a href="<%= @obj.url %>" onclick="<% @obj.increment_clicks() %>">A link</a>

(in obj model)

def increment_clicks
   self.clicks += 1;
   self.save!
end

Now obviously this example doesn't work (it will just always call increment_clicks(), because the ERb has no notion of the 'onclick' condition), but is something like this possible? (I know you can do this by say, setting up a controller method that will process this logic and then redirect you to the URL -- but this isn't what I want. I essentially want to call ruby functions asynchronously. Or, if that's not possible, call javascript that can interact with my database )

Re: OnClick/OnLoad + Ruby Function?

The client-side javascript doesn't have access to the server-side ruby objects. (The Ruby code is processed before it is rendered and sent to the client).

You can use the Ajax functions (Request and Updater) to call a controller action on the server to increment the clicks.

Toby Hede
===================================================
FiniteStateMachine - Software Development for Social Networks
===================================================

Re: OnClick/OnLoad + Ruby Function?

Client-side logic has no interaction with server-side logic other than through requests.  You'll have to use ajax to accomplish what you are talking about.

Kyle Peyton - Web Developer
Santa Clara, CA - Startontop

Re: OnClick/OnLoad + Ruby Function?

Thanks guys. Using

onclick="<%= remote_function( :url => { :controller => 'images', :action 'increment_clicks', :id => image.id }) %>"

I accomplished what I wanted to do (The RESTful version also worked). However, I ran into a slightly annoying problem, in that rails would try to render the template for my controller action (e.g. increment_clicks.rhtml) and obviously fail. Is there a way around this? To make it so rails will just call the action but not try to render anything?

Also, sometimes after refreshing my image index, my Image.find(:all) would return the images in a different order. Does rails use something else besides the id field to sort the results?

Re: OnClick/OnLoad + Ruby Function?

So I solved my render problem by simply putting in blank rjs templates for the function names (since it looks there first).

My problem now is that sometimes my onclick / onload events sometimes don't fire properly. I think it has something to do with other actions still being processed, because as far as I can tell they fire correctly if I just let the page load long enough. Is there any way to make it so that the javascript will execute successfully eventually regardless of whatever else is being processed?