Rails 3 自定义 FormBuilder 参数 [英] Rails 3 Custom FormBuilder Parameters
本文介绍了Rails 3 自定义 FormBuilder 参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我为我的应用程序创建了一个自定义 FormBuilder,但我不明白为什么我需要按如下方式传递两个参数:
I create a custom FormBuilder for my application, but I dont understand why I need to pass tow parameters as follow:
f.text_field :my_model, :my_field
这是我的构建器:
class AceBuilder < ActionView::Helpers::FormBuilder
%w[text_field password_field text_area].each do |method_name|
define_method(method_name) do |object_name, method, *args|
options = args.extract_options!
@template.content_tag(:div, :class => "control-group #{@object.errors[method].length > 0 ? 'error' : ''}") do
@template.concat(
@template.content_tag(:label,
options[:label] || method.to_s.humanize,
:class => 'control-label',
:for => "#{object_name}_#{method}"))
@template.concat(
@template.content_tag(:div,
:class => "controls") do
@template.concat(super(method))
@template.concat(
@template.content_tag(:span,
@object.errors[method].join,
:for => "#{object_name}_#{method}",
:class => "help-inline"
)
)
end
)
end
end
end
我知道
define_method(method_name) do |object_name, method, *args|
有两个参数,所以我的问题是:
has two parameters, so my question is:
我该如何编写这个 FormBuilder,这样我就可以这样称呼它:
How can I write this FormBuilder, such a way that I can call it like this:
f.text_field :my_field
谢谢.
推荐答案
这很容易,在我意识到如何:用 @object_name 替换 object_name
That was easy, after I realize how: replace object_name by @object_name
class AceBuilder < ActionView::Helpers::FormBuilder
%w[text_field password_field text_area].each do |method_name|
define_method(method_name) do |method, *args|
options = args.extract_options!
@template.content_tag(:div, :class => "control-group #{@object.errors[method].length > 0 ? 'error' : ''}") do
@template.concat(
@template.content_tag(:label,
options[:label] || method.to_s.humanize,
:class => 'control-label',
:for => "#{@object_name}_#{method}"))
@template.concat(
@template.content_tag(:div,
:class => "controls") do
@template.concat(super(method))
@template.concat(
@template.content_tag(:span,
@object.errors[method].join,
:for => "#{@object_name}_#{method}",
:class => "help-inline"
)
)
end
)
end
end
end
这篇关于Rails 3 自定义 FormBuilder 参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文