Based on guides.rubyonrails.org
Most Simple
use xxx_tag
<%=
form_tag("/search", method: "get") do %>
<%= label_tag(:q, "Search for:")
%>
<%= text_field_tag(:q) %>
<%= submit_tag("Search") %>
<% end %>
Passing controller and action
form_tag(controller:
"people", action: "search", method: "get", class:
"nifty_form")
#
=> '
#OR
form_tag({controller:
"people", action: "search"}, method: "get",
class: "nifty_form")
#
=> '
Different helpers
Checkboxs
<%=
check_box_tag(:pet_cat) %>
<%=
label_tag(:pet_cat, "I own a cat") %>
Result:
<input id="pet_cat" name="pet_cat" type="checkbox" value="1" />
<label for="pet_cat">I own a cat</label>
RadioBox
<%=
radio_button_tag(:age, "child") %>
<%=
label_tag(:age_child, "I am younger than 21") %>
Result:
<input id="age_child" name="age" type="radio" value="child" />
<label for="age_child">I am younger than 21</label>
Others
<%=
text_area_tag(:message, "Hi, nice site", size: "24x6")
%>
<%=
password_field_tag(:password) %>
<%=
hidden_field_tag(:parent_id, "5") %>
<%=
search_field(:user, :name) %>
<%=
telephone_field(:user, :phone) %>
<%=
date_field(:user, :born_on) %>
<%=
datetime_field(:user, :meeting_time) %>
<%=
datetime_local_field(:user, :graduation_day) %>
<%=
month_field(:user, :birthday_month) %>
<%=
week_field(:user, :birthday_week) %>
<%=
url_field(:user, :homepage) %>
<%=
email_field(:user, :address) %>
<%=
color_field(:user, :favorite_color) %>
<%=
time_field(:task, :started_at) %>
Dealing with Model Objects
These kind of helpers does
not use the sufix "_tag"
Ex: <%=
text_field(:person, :name) %>
Result:
<input id="person_name" name="person[name]" type="text" value="Henry"/>
Binding a Form to an Object
In controller
def
new
@article = Article.new
end
In view
<%=
form_for @article, url: {action: "create"}, html: {class:
"nifty_form"} do |f| %>
<%= f.text_field :title %>
<%= f.text_area :body, size:
"60x12" %>
<%= f.submit "Create" %>
<%
end %>
If I have an association it
is possible to define a form to the associated object
<%= form_for
@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 %>
Result:
<form accept-charset="UTF-8" action="/people/create" class="new_person" id="new_person" method="post">
<input id="person_name" name="person[name]" type="text" />
<input id="contact_detail_phone_number" name="contact_detail[phone_number]" type="text" />
</form>
How do forms with PATCH, PUT, or DELETE methods work?
Some browsers don't have
PATCH, then Rails emulate this method using a hidden parameter in a POST search
form_tag(search_path, method:
"patch")
results:
<form accept-charset="UTF-8" action="/search" method="post">
<div style="margin:0;padding:0">
<input name="_method" type="hidden" value="patch" />
<input name="utf8" type="hidden" value="✓" />
<input name="authenticity_token" type="hidden" value="f755bb0ed134b76c432144748a6d4b7a7ddf2b71" />
</div>
...
Select and option
The simplest way
<%=
select_tag(:city_id, '...') %>
ex:
<%=
options_for_select([['Lisbon', 1], ['Madrid', 2], ...]) %>
Together
<%=
select_tag(:city_id, options_for_select(...)) %>
ex:
<%=
options_for_select([['Lisbon', 1, {'data-size' => '2.8 million'}],
['Madrid', 2, {'data-size' => '3.2 million'}]], 2) %>
output:
<option value="1" data-size="2.8 million">Lisbon</option>
<option value="2" selected="selected" data-size="3.2 million">Madrid</option>
Select dealing with model
# controller:
@person
= Person.new(city_id: 2)
# view:
<%=
select(:person, :city_id, [['Lisbon', 1], ['Madrid', 2], ...]) %>
#OR
#
select on a form builder
<%=
person.select(:city_id, ...) %>
Options from a Array or
Collection
<% cities_array
= City.all.map { |city| [city.name, city.id] } %>
<%=
options_for_select(cities_array) %>
#Better
<%=
options_from_collection_for_select(City.all, :id, :name) %>
All together
<%=
collection_select(:person, :city_id, City.all, :id, :name) %>
Date and Time
Barebones Helpers
select_date,
select_time and select_datetime
<%= select_date
Date.today, prefix: :start_date %>
Equivalent Model Object
Helper
date_select,
time_select and datetime_select
<%= date_select
:person, :birth_date %>
#OR
<%=
person.date_select :birth_date %>
Uploading Files
The rendered form's encoding
MUST be set to "multipart/form-data"
With form_for it is
done automaticaly
With form_tag, you
must set it yourself
ex:
<%= form_for
@person do |f| %>
<%= f.file_field :picture %> ----->
params[:picture]
<% end %>
<%= form_tag({action:
:upload}, multipart: true) do %>
<%= file_field_tag 'picture' %>
---->params[:person][:picture]
<% end %>
Saving
Picture is save in
#{Rails.root}/public/uploads
def upload
uploaded_io = params[:person][:picture]
File.open(Rails.root.join('public',
'uploads', uploaded_io.original_filename), 'wb') do |file|
file.write(uploaded_io.read)
end
end
With ajax
It is more complex
than other forms.
Parameters and conventions
HTML doesn't have any
structured data, just get pairs name-value
Basic Structure
#Input
<input id="person_name" name="person[name]" type="text" value="Henry"/>
#Params
{'person'
=> {'name' => 'Henry'}}
#Input
<input id="person_address_city" name="person[address][city]" type="text" value="New York"/>
#Params
{'person'
=> {'address' => {'city' => 'New York'}}}
Using Form Helper
<%= form_for
@person do |f| %>
<%= f.text_field :name %>
<% @person.addresses.each do |address|
%>
<%= f.fields_for address, index: address
do |address_form|%>
<%= address_form.text_field :city
%>
<% end %>
<% end %>
<% end %>
#Params
{'person'
=> {'name' => 'Bob', 'address' => {'23' => {'city' => 'Paris'},
'45' => {'city' => 'London'}}}}
Form to external resources
# It is possible to
pass an external token to access the external resource
<%= form_for
@invoice, url: external_url, authenticity_token: 'external_token' do |f| %>
Form contents
<% end %>
# OR
authenticity_token: false
Complex forms
#uses
accepts_nested_attributes_for
class Person <
ActiveRecord::Base
has_many :addresses
accepts_nested_attributes_for :addresses
end
class Address <
ActiveRecord::Base
belongs_to :person
end
This creates an
addresses_attributes= method
And creates a form with a
Person and its associates address
<%= form_for
@person do |f| %>
Addresses:
<%= f.fields_for :addresses do
|addresses_form| %>
<%= addresses_form.label :kind %>
<%= addresses_form.text_field :kind
%>
<%= addresses_form.label :street
%>
<%= addresses_form.text_field
:street %>
...
<% end %>
<%
end %>
Nenhum comentário:
Postar um comentário