2

What is the best way to override form_for?

For example, in every form_for(@post),

I would like to automatically set the <form> id attribute to @post.object_id,

and add the following field: hidden_field_tag :form_id, @post.object_id

Can I do this using alias_method_chain?

deb
  • 12,326
  • 21
  • 67
  • 86

3 Answers3

3

Technically, you could probably achieve your goal by using alias_method_chain, but it would require parsing the form and injecting/modifying the content, which could get really ugly, really fast.

Instead, I'd suggest overriding form_for with your own custom version (the original source can be seen here http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-form_for by clicking "show source" at the bottom).

One way to achieve this is described in a post I wrote recently: http://davidsulc.com/blog/2011/05/01/self-marking-required-fields-in-rails-3/

The difference being: instead of overriding the label method, you'll be rewriting the form_for method.

P.S.: out of curiosity, why do you need to expose the object_id?

David Sulc
  • 25,946
  • 3
  • 52
  • 54
  • Are there any issues with using object_id? – deb May 25 '11 at 20:03
  • Well, `object_id` is basically Ruby's internal business. There are few cases in Ruby where you need to use `object_id`, and I can't think of a reason why you'd need to expose it in Rails. Also, for a given database record, `oject_id` will basically be different each time it is loaded into memory (you can try that by calling `Post.first.object_id` repeatedly in the Rails console). I'm just thinking that there might be a better way to achieve your goal (whatever it may be) than using the `object_id` attribute... – David Sulc May 26 '11 at 12:47
2

This should work (it worked for me):

  <%= hidden_field(:post :form_id, :value => @post.object_id) %>
0

In a Rails helper you can simply do something like:

def form_for(record, options = {}, &block)
  options[:id] = record.class.to_s + '-' + record.id
  super
end
Dorian
  • 22,759
  • 8
  • 120
  • 116