Observing Fields
For one of my apps I wanted a text field to be updated with a new default value
whenever a new entry was selected in a select field. “Great”, I thought, “another thing made
possible through Rail’s great AJAX support”. The observe_field function promised
to be exactly what I was looking for.
However, I couldn’t figure out how to use the :with parameter correctly
to pass the selected value to my code at first. The
documentation didn’t say
too much on this point, either.
Finally, I realized that you can put a java-script expression here that gets evaluated and the result will be used as a parameter string. The trick is to simply construct a complete query string of the form “name=value”. This is what I have in my view:
<%= observe_field "ftp_select", :frequency => 1,
:update => "element_doc_root",
:url => { :action => "ftp_account_changed" },
:with => "'ftp='+value" %>
“ftp_select” is the DOM id of the select field. Notice the :with parameter. This
evaluates to a string like “ftp=425”, so in my controller code I can access this as
@params["ftp"].
BTW, the default value for :with is just “value”. I’m not sure how you are supposed to
retrieve this form your @params hash, but maybe there is some rationale hidden from me
behind this after all (like most of the time when I don’t get something)...