rails form helpers

本文详细介绍了如何使用Rails的Helper方法创建表单元素,包括文本框、选择框等,以及如何处理文件上传和编辑多模型对象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<%= text_field(:person, :name) %>

<input id="person_name" name="person[name]" type="text" value="Henry"/>


You can create a similar binding without actually creating <form> tags with the fields_for helper. This is useful for editing additional model objects with the same form. For example if you had a Person model with an associated ContactDetail model you could create a form for creating both like so:

<%= form_for :person, @person, :url => { :action => "create" } do |person_form| %>
  <%= person_form.text_field :name %>
  <%= fields_for @person.contact_detail do |contact_details_form| %>
    <%= contact_details_form.text_field :phone_number %>
  <% end %>
<% end %>

## Creating a new article
# long-style:
form_for(:article, @article, :url => articles_path)
# same thing, short-style (record identification gets used):
form_for(@article)
 
## Editing an existing article
# long-style:
form_for(:article, @article, :url => article_path(@article), :html => { :method => "put" })
# short-style:
form_for(@article)

If you have created namespaced routes, form_for has a nifty shorthand for that too. If your application has an admin namespace then
form_for [:admin, @article]

<%= select_tag(:city_id, options_for_select(...)) %>

<%= options_for_select([['Lisbon', 1], ['Madrid', 2], ...], 2) %>
 
output:
 
<option value="1">Lisbon</option>
<option value="2" selected="selected">Madrid</option>
...


Select Boxes for Dealing with Models

 Consistent with other form helpers, when dealing with models you drop the _tag suffix from select_tag:
# controller:
@person = Person.new(:city_id => 2)

# view:
<%= select(:person, :city_id, [['Lisbon', 1], ['Madrid', 2], ...]) %>

# select on a form builder
<%= f.select(:city_id, ...) %>

Option Tags from a Collection of Arbitrary Objects
<%= options_from_collection_for_select(City.all, :id, :name) %>

<%= collection_select(:person, :city_id, City.all, :id, :name) %>

Uploading Files

<%= form_tag({:action => :upload}, :multipart => true) do %>
  <%= file_field_tag 'picture' %>
<% end %>
 
<%= form_for @person, :html => {:multipart => true} do |f| %>
  <%= f.file_field :picture %>
<% end %>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值