gpt4 book ai didi

ruby-on-rails - 向 FormBuilder 添加一个方法,该方法调用一个渲染部分的辅助方法

转载 作者:行者123 更新时间:2023-12-04 06:00:33 25 4
gpt4 key购买 nike

所以我有这个辅助方法,对吧?

def table_form_field(name_or_options = nil, *args, &block)
# ...
render :partial => "snippets/table_form_field", :locals => options
end

很好,除了有时我想将它与表单生成器一起使用,
为此,我必须这样称呼它:
table_form_field(:foo, :form_builder => f) do |name|
f.text_field name
end

必须手动指定 :form_builder 很烦人。所以我的目标是扩展 ActionView::Helpers::FormBuilder并为其添加一个新方法,如下所示:
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多变的。

例如,我将创建一个继承自 ActionView::Helpers::FormBuilder 的自定义表单构建器

class MyFormBuilder < ActionView::Helpers::FormBuilder
def table_form_field(*attrs, &block)
@template.table_form_field(*attrs, &block)
end
end

然后在您的 form_for 中,您可以告诉它使用您的自定义表单构建器
<%= form_for @myobject, :builder => MyFormBuilder do |f| %>
<%= f.table_form_field :myfield do %>
<% end %>
<%= end %>

关于ruby-on-rails - 向 FormBuilder 添加一个方法,该方法调用一个渲染部分的辅助方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7238798/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com