30 Sep, 2007

Published at 09:29PM

Tagged with problems, programming, rails, and tips

This post has 2 comments

Be careful when using observe_form

A recent run-in with observe_form left me puzzled and frustrated for a while, so I feel obligated to make note of it (and hopefully spare someone else the aggravation).

It turns out when using observe_form you must specify the :update option, or no form parameters are sent to the server. Here’s a quick example of something similar to what I was doing, which doesn’t work:

<% form_tag '', { :id => 'options_form' } do -%>
  <%= radio_button_tag :option, 1 -%>
  <%= radio_button_tag :option, 2 -%>
  <%= radio_button_tag :option, 3 -%>
<% end -%>

<div id="inspection"></div>

<%= observe_form :options_form, :url => update_options_path -%>

Any click/change to those radio buttons and the ajax call was made to the appropriate action. However, no parameters were sent. Here’s basically what I had in my controller:

1
2
3
4
5
def update_options
  render :update do |page|
    page[:inspection].replace_html params.inspect
  end
end

This returned {"controller"=>"...", "action"=>"..."}, with no form parameters. After a bit of head scratching and a few “I don’t know why this would fix it, but…” moments, it turns out that you can’t leave the :update option out of the observe_form call. Changing it to…

<%= observe_form :options_form, :url => update_options_path, :update => 'inspection' -%>

...and…

1
2
3
def update_options
  render :text => params.inpsect
end

worked perfectly. Now I can do what I need to do with the parameters, and move on with my life. Time to commit and go to bed. Goodnight.

TODO: figure out how to get observe_form to work with RJS, as I need to modify CSS class names and update multiple things based on params.

Comments

flyingchen Tuesday, 23 Oct, 2007 Posted at 12:14AM

do you sure that you have found the key ? but i do follow you wrote,it still can not work well:( can you sent me a simple demo,thx a lot flyingmain@gmail.com

frustratedchamp Tuesday, 04 Dec, 2007 Posted at 09:03PM

Workaround(RJS): (http://railsforum.com/viewtopic.php?pid=39156)

Do you have something to say about this post?
Retype the image to the right Spam Hint: Are You Human? Textile Formatting Tips

or

Ryan Heath | Site Management A Ruby on Rails production.

This site is a Formed Function. Formed Function LLC | @formedfunction | Get in Touch