简体   繁体   English

如何修改 Rails 3 表单生成器

[英]How to modify Rails 3 form builder

What is the best way to override form_for ?覆盖form_for的最佳方法是什么?

For example, in every form_for(@post) ,例如,在每个form_for(@post)中,

I would like to automatically set the <form> id attribute to @post.object_id ,我想自动将<form> id 属性设置为@post.object_id

and add the following field: hidden_field_tag:form_id, @post.object_id并添加以下字段: hidden_field_tag:form_id, @post.object_id

Can I do this using alias_method_chain ?我可以使用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.从技术上讲,您可能可以通过使用alias_method_chain来实现您的目标,但它需要解析表单并注入/修改内容,这可能会变得非常难看,非常快。

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).相反,我建议用您自己的自定义版本覆盖form_for (原始来源可以在这里看到http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-form_for通过单击“显示来源”在底部)。

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/我最近写的一篇文章中描述了实现此目的的一种方法: 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.不同之处在于:您将重写form_for方法,而不是覆盖label方法。

PS: out of curiosity, why do you need to expose the object_id ? PS:出于好奇,为什么需要公开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:在 Rails 助手中,您可以简单地执行以下操作:

def form_for(record, options = {}, &block)
  options[:id] = record.class.to_s + '-' + record.id
  super
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM