Ruby-on-rails 在 Rails 表单中使用 textarea 助手

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4141069/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 23:36:42  来源:igfitidea点击:

Using the textarea helper in Rails forms

ruby-on-railsformshelper

提问by maria

Why does this code show an error in text area?

为什么此代码在文本区域显示错误?

<%= form_for(:ad, :url => {:action => 'create'}) do |f| %>
  <%= f.text_field(:name) %>
  <%= f.text_area_tag(:text, "", :size => "50x10") %>
  <%= submit_tag("Submit") %>
<% end %>

回答by meagar

The FormHelpermethod is text_area, not text_area_tag.

FormHelper方法是text_area,不text_area_tag

Use either of the following:

使用以下任一方法:

<%= f.text_area(:text, size: '50x10') %>

or:

或者:

<%= text_area_tag(:ad, :text, size: '50x10') %>

回答by Adam Lassek

The fvariable that you are creating in the first line is a reference to your FormBuilder. By default it references ActionView::Helpers::FormBuilderor you can create your own.

f您在第一行中创建的变量是对FormBuilder的引用。默认情况下它引用,ActionView::Helpers::FormBuilder或者您可以创建自己的。

The FormBuilder helper for textareas is called text_area. FormBuilder helpers are smarter than regular HTML helpers. Rails models can be nested logically, and your forms can be written to reflect this; one of the primary things FormBuilder helpers do is keep track of how each particular field relates to your data model.

用于 textareas 的 FormBuilder 助手称为text_area。FormBuilder 助手比普通的 HTML 助手更聪明。Rails 模型可以逻辑嵌套,您可以编写表单来反映这一点;FormBuilder 助手所做的主要事情之一是跟踪每个特定字段与您的数据模型的关系。

When you call f.text_area, since fis associated with a form named :adand the field is named :textit will generate a field named ad[text]. This is a parameter convention that will be automatically parsed into a Hash on the server: { :ad => { :text => "value" } }instead of a flat list of parameters. This is a huge convenience because if you have a Model named Ad, you can simply call Ad.create(params[:ad])and all the fields will be filled in correctly.

当您调用时f.text_area,由于f与一个名为的表单:ad和该字段相关联,:text它将生成一个名为 的字段ad[text]。这是一个参数约定,将在服务器上自动解析为哈希:{ :ad => { :text => "value" } }而不是参数的平面列表。这是一个巨大的便利,因为如果您有一个名为 的模型Ad,您只需调用即可Ad.create(params[:ad]),所有字段都将被正确填写。

text_area_tagis the generic helper that isn't connected to a form automatically. You can still make it do the same things as FormBuilder#text_area, but you have to do it manually. This can be useful in situations that a FormBuilder helper isn't intended to cover.

text_area_tag是不自动连接到表单的通用助手。你仍然可以让它做与 相同的事情FormBuilder#text_area,但你必须手动完成。这在 FormBuilder 助手不打算涵盖的情况下很有用。