Forum: Ruby on Rails Understanding observe_form...

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Jeff C. (Guest)
on 2006-04-08 23:38
Hi all,

I'm trying to understand the workings of the observe_form function.

In my application I have a search form with a number of parameters, and
I want to have a live search counter on screen, so as the user chooses
different parameters, she can see a live count of how many search
results match.

What I'm not clear on is how to use the "with" option, and what I've
done is a slightly bizarre hack that works, but is hardly best
practices.  If someone could help me be clear on what exactly the "with"
option does and how to use it, I'd be indebted.

In my view, I have a form:

  <%= start_form_tag({:controller => 'houses', :action => 'find'}, {:id
=> 'advanced_search', :method => :get}) %>
  <p>How much are you willing to spend?</p>
  <%= radio_button_tag :price, "small" %> a bit
  <%= radio_button_tag :price,  "medium" %> a lot
  <%= radio_button_tag :price, "any" %> the sky's the limit!

  ..other options follow..
<%= end_form_tag %>

The first option is "price", a set of radiobuttons, but it's just the
first option and there are several more input fields in the form.

After my form, I have the observe_field tag:

<%= observe_form( 'advanced_search',
  :frequency => 1,
  :with => "price",
  :url => {:action => 'search_results'}) %>

After a lot of trial and error, I listed the "with" value as "price",
because for some reason it seemed be only the price value that was
passed.  Whatever other options were in the form, whatever I listed
under "with" became an entry in my params hash with the value
"price=_value_of_price_field".

Originally I gave the option :with => "advanced_search", because that's
my form tag.  Then if the "price" option clicked was "any", when I found
in the params hash was:

params[:advanced_search]  #=>  "price=any"

The other form options were included in the params as I would expect,
just as if my form had actually been submitted.  Only the first fields,
the price entry, was different.

To workaround this, I used :with => "price" in my observe_form, and
added the following to my search_results action:

params[:price].gsub!("price=", "") if params[:price]

Now whether the search results are submitted as normal, or with this odd
behavior from the remote call, it works as it should.  But why?

I hope this example has been clear enough, it's a hard thing to
describe. Perhaps someone could give an example of the real usage of
"with" in the observe_form function.  I honestly don't understand what
is written in the API docs, and it took a lot of trial and error to hack
together something that functioned.

Thanks,
Jeff C.man
This topic is locked and can not be replied to.