尝试扩展 ActionView::Helpers::FormBuilder
我试图通过将一些逻辑移入 FormBuilder 来干燥一些代码。在阅读了有关如何选择和替代表单生成器的文档后,对我来说逻辑解决方案似乎是这样的。
在视图中
<% form_for @event, :builder => TestFormBuilder do |f| %>
<%= f.test %>
<%= f.submit 'Update' %>
<% end %>
,然后在 app/helpers/application_helper.rb 中,
module ApplicationHelper
class TestFormBuilder < ActionView::Helpers::FormBuilder
def test
puts 'apa'
end
end
end
但是,这在“form_for”处给了我一个错误,
uninitialized constant ActionView::Base::CompiledTemplates::TestFormBuilder
我在哪里做错了?
I am trying to DRY up some code by moving some logic into the FormBuilder. After reading the documentation about how to select and alternative form builder the logical solution for me seemed to be something like this.
In the view
<% form_for @event, :builder => TestFormBuilder do |f| %>
<%= f.test %>
<%= f.submit 'Update' %>
<% end %>
and then in app/helpers/application_helper.rb
module ApplicationHelper
class TestFormBuilder < ActionView::Helpers::FormBuilder
def test
puts 'apa'
end
end
end
This, however, gives me an error at the "form_for"
uninitialized constant ActionView::Base::CompiledTemplates::TestFormBuilder
Where am I doing it wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试使用:
try with :
构建器类可以放置在模块文件中,内部或/和外部模块定义中,如下所示:
将构建器附加到表单的正确方法是:
这是在表单上设置构建器选项的帮助器方法:
现在,有一种可选方法将构建器附加到form:
最后,自定义构建器可以放置在单独的文件夹中,例如“app/builders”,但这需要手动将此路径添加到应用程序环境中。对于 Rails 2.3.x,设置:
Builder class can be placed in module file, inside or/and outside module definition, like this:
Proper way to attach builder to form is:
Here is helper method for setting builder option on form:
Now, there is optional way to attach builder to form:
Finally, custom builders can be placed in separated folder, for example "app/builders", but this demands to manually add this path into application environment. For Rails 2.3.x, set:
正如您在 http://guides.rubyonrails.org/configuring.html# 中看到的配置动作视图,您可以为整个应用程序设置默认的FormBuilder类。在你的情况下:
As you can see in http://guides.rubyonrails.org/configuring.html#configuring-action-view, you can set a default FormBuilder-class for your whole application. In your case: