在 Rails 表单中使用 textarea 助手
为什么此代码在文本区域显示错误?
<%= form_for(:ad, :url => {:action => 'create'}) do |f| %>
<%= f.text_field(:name) %>
<%= f.text_area_tag(:text, "", :size => "50x10") %>
<%= submit_tag("Submit") %>
<% end %>
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 %>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
FormHelper
方法是text_area
,而不是text_area_tag
。使用以下任一:
或:
The
FormHelper
method istext_area
, nottext_area_tag
.Use either of the following:
or:
您在第一行中创建的
f
变量是对 FormBuilder 的引用。默认情况下,它引用ActionView::Helpers::FormBuilder
或者您可以创建自己的。文本区域的 FormBuilder 帮助程序称为
text_area
。 FormBuilder 帮助器比常规 HTML 帮助器更智能。 Rails 模型可以逻辑嵌套,并且可以编写您的表单来反映这一点; FormBuilder 助手所做的主要事情之一是跟踪每个特定字段与数据模型的关系。当您调用
f.text_area
时,由于f
与名为:ad
的表单关联,并且该字段名为:text 它将生成一个名为
ad[text]
的字段。这是一个参数约定,将在服务器上自动解析为哈希:{ :ad =>; {:文本=> “value” } }
而不是简单的参数列表。这是一个巨大的便利,因为如果您有一个名为Ad
的模型,您只需调用Ad.create(params[:ad])
即可填充所有字段正确。text_area_tag
是通用助手,不会自动连接到表单。您仍然可以让它执行与FormBuilder#text_area
相同的操作,但您必须手动执行。这在 FormBuilder 帮助器不打算涵盖的情况下非常有用。The
f
variable that you are creating in the first line is a reference to your FormBuilder. By default it referencesActionView::Helpers::FormBuilder
or you can create your own.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.When you call
f.text_area
, sincef
is associated with a form named:ad
and the field is named:text
it will generate a field namedad[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 namedAd
, you can simply callAd.create(params[:ad])
and all the fields will be filled in correctly.text_area_tag
is the generic helper that isn't connected to a form automatically. You can still make it do the same things asFormBuilder#text_area
, but you have to do it manually. This can be useful in situations that a FormBuilder helper isn't intended to cover.