向 FormBuilder 添加一个调用辅助方法的方法,该方法呈现部分 [英] Adding a method to FormBuilder that calls a helper method that renders a partial
问题描述
所以我有这个辅助方法,对吗?
So I've got this helper method, right?
def table_form_field(name_or_options = nil, *args, &block)
# ...
render :partial => "snippets/table_form_field", :locals => options
end
这很好,但有时我想将它与表单构建器一起使用,要做到这一点,我必须这样称呼它:
It's nice, except sometimes I want to use it with a form builder, and to do that I'd have to call it like this:
table_form_field(:foo, :form_builder => f) do |name|
f.text_field name
end
必须手动指定 :form_builder 很烦人.所以我的目标是扩展 ActionView::Helpers::FormBuilder
并为其添加一个新方法,如下所示:
It's annoying to have to specify :form_builder manually. So my goal is to extend ActionView::Helpers::FormBuilder
and add a new method to it, like so:
class ActionView::Helpers::FormBuilder
def table_form_field(name_or_options, options, &block)
if name_or_options.is_a?(Hash)
name_or_options[:form_builder] = self
else
options[:form_builder] = self
end
# But... how can I call the helper?
# Hmm, I'll try this:
klass = Class.new do
include ApplicationHelper
end
klass.new.send(:table_form_field, name_or_options, options, &block)
# Thank you, Mario, but your princess is in another castle!
#
# Basically, this tries to call render, and for obvious
# reasons, klass doesn't know how to render.
#
# So... what do I do?
end
end
推荐答案
您可以从表单构建器中访问名为 @template
的实例变量,因此您只需调用 table_form_field
在 @template
变量上.
You can access an instance variable called @template
from within form builders so you can just call table_form_field
on the @template
variable.
例如,我将创建一个继承自 ActionView::Helpers::FormBuilder 的自定义表单构建器
For example, I would create a custom form builder that inherits from ActionView::Helpers::FormBuilder
class MyFormBuilder < ActionView::Helpers::FormBuilder
def table_form_field(*attrs, &block)
@template.table_form_field(*attrs, &block)
end
end
然后在你的 form_for 中你可以告诉它使用你的自定义表单构建器
Then in your form_for you can tell it to use your custom form builder
<%= form_for @myobject, :builder => MyFormBuilder do |f| %>
<%= f.table_form_field :myfield do %>
<% end %>
<%= end %>
这篇关于向 FormBuilder 添加一个调用辅助方法的方法,该方法呈现部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!