2013-05-17 67 views
0

我創建我的應用程序自定義FormBuilder,但我不明白爲什麼我需要通過拖參數如下:的Rails 3自定義FormBuilder參數

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| 

有兩個參數,所以我的問題是:

我怎麼可以這樣寫FormBuilder,這樣的方式,我可以這樣調用:

f.text_field :my_field 

感謝。

回答

0

這很簡單,我以後怎麼實現:通過@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 
更換OBJECT_NAME