如何修改 Rails 3 表单生成器
覆盖 form_for
的最佳方法是什么?
例如,在每个 form_for(@post)
中,
我想自动将
并添加以下字段:hidden_field_tag :form_id, @post.object_id
我可以使用 alias_method_chain
执行此操作吗?
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
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
从技术上讲,您可能可以通过使用
alias_method_chain
来实现您的目标,但它需要解析表单并注入/修改内容,这可能会变得非常难看,而且速度非常快。相反,我建议使用您自己的自定义版本覆盖
form_for
(原始来源可以在此处查看 http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-form_for(点击底部的“显示源代码”)。我最近写的一篇文章描述了实现此目的的一种方法:http://davidsulc.com/blog/2011/05/01/self-marking-required-fields-in-rails-3/
区别在于:为了重写
label
方法,您将重写form_for
方法。PS:出于好奇,为什么需要公开
object_id
?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 theform_for
method.P.S.: out of curiosity, why do you need to expose the
object_id
?这应该有效(它对我有用):
This should work (it worked for me):
在 Rails 助手中,您可以简单地执行以下操作:
In a Rails helper you can simply do something like: