How to modify Rails 3 form builder
What is the best way to override form_for
?
For example, in every form_for(@post)
,
I would like to automatically set the <fo开发者_运维知识库rm>
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
?
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
?
This should work (it worked for me):
<%= hidden_field(:post :form_id, :value => @post.object_id) %>
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
精彩评论