Sunday, June 13, 2010

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.

 1 # used internally to generate the form for the en_place editor  2 def en_place_form(record_or_array, field_name,   3                   options = {}, html_options = {})  4   # process the options, and other misc details  5   form_block = proc do  6     form_for(record_or_array, :html => html_options) do |f|  7       concat(f.text_field field_name, :class => "en_place")  8       concat(f.submit "Update")  9     end       10   end 11   is_haml? ? capture_haml(&form_block) : capture(&form_block) 12 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.

Posted via web from The Web and all that Jazz

No comments:

Post a Comment