Rails自定义表单生成器。自定义text_field

时间:2013-07-15 22:18:35

标签: ruby ruby-on-rails-3 ruby-on-rails-3.2 formbuilder

我正在尝试在rails中创建自定义表单构建器以转换此代码

    <div class="row collapse">
      <div class="large-4 columns">
        <%= builder.label :vacancy_title, "Title of the Vacancy", class: "right inline" %>
      </div>
      <div class="large-8 columns">
        <%= builder.text_field :vacancy_title, class: "tiny" %>
      </div>
    </div>

简单

<%= builder.t_field :vacancies, "Label title" %>

我正在尝试这段代码没有运气,只是显示标签。

#form_builders/custom_form_builder.rb
class CustomFormBuilder < ActionView::Helpers::FormBuilder
def t_field(name, title, *args)
   @template.content_tag :div, class: "row collapse" do
     @template.content_tag :div, class: "large-8 columns" do
   text_field_tag(name, *args)
     end

   @template.content_tag :div, class: "large-4 columns" do
     @template.content_tag :h5 do
       label(title, options[:label], class: "right inline")
     end
   end

 end
end

text_field_tag(name,* args)显然有问题,但我不知道如何声明输入。我在rubyapi Helpers :: FormBuilder

上找不到任何文档

解决

感谢Levi Stanley,我用以下代码解决了这个问题。我需要将text_field_tag(name, *args)更改为text_field_tag("#{object_name}[#{name}]"),将label(title, options[:label], class: "right inline")更改为label(name, title, *args, class: "right"),以使表单适用于嵌套属性。

class LabeledFormBuilder < ActionView::Helpers::FormBuilder
  def t_field(name, title, *args)
    @template.content_tag :div, class: "row collapse" do
      (@template.content_tag :div, class: "large-4 columns" do
        @template.content_tag :h5 do
          label(name, title, *args, class: "right")
        end
      end) +
      (@template.content_tag :div, class: "large-8 columns" do
        @template.text_field_tag("#{object_name}[#{name}]")
      end)
    end
  end
end

1 个答案:

答案 0 :(得分:1)

您需要将内部div的content_tag连接在一起。 content_tag方法使用块的返回值来确定其内容。您正在运行包含text_field_tag的div的代码,但实际上并未将其包含在外部“row collapse”div中,因为它不包含在块的返回值中。

#form_builders/custom_form_builder.rb
class CustomFormBuilder < ActionView::Helpers::FormBuilder
  def t_field(name, title, *args)

    @template.content_tag :div, class: "row collapse" do
      (@template.content_tag :div, class: "large-8 columns" do
        text_field_tag(name, *args)
      end) +

      (@template.content_tag :div, class: "large-4 columns" do
        @template.content_tag :h5 do
          label(title, options[:label], class: "right inline")
        end
      end)
    end
  end
end