How to generate forms in rails helpers

This is more of a note to myself than anything, since I find myself having to generate forms from helpers in Rails every once in a while. This is for Rails 2.3.5. I don’t know if Rails 3 has this problem.

I wrote my own in-place editor for model fields, and it generates a form through a helper.

# used internally to generate the form for the en_place editor
def en_place_form(record_or_array, field_name, 
                  options = {}, html_options = {})
  # process the options, and other misc details
  form_block = proc do
    form_for(record_or_array, :html => html_options) do |f|
      concat(f.text_field field_name, :class => "en_place")
      concat(f.submit "Update")
    end      
  end
  is_haml? ? capture_haml(&form_block) : capture(&form_block)
end

All you have to do is capture a block that calls form_for or form_tag. And then inside of the form, you can to call concat on the fields that you want inside of the form.

Then lastly, you have to capture the block. If you’re using haml, you have to call capture_haml() instead.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s