SlideShare una empresa de Scribd logo
1 de 21
Descargar para leer sin conexión
Understanding Form Helpers
Bruno Almeida
● Form tag
● Form to an object
● Select
● Customize fields
● Nested forms
Let’s begin
Form tag
http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html
form_tag
<%= form_tag do %>
Form contents
<% end %>
<form action="/" accept-charset="UTF-8" method="post">
<input name="utf8" type="hidden" value="&#x2713;" />
<input type="hidden" name="authenticity_token" value="
jzi1o/1Wl8yTZ2e1Z3QE99BFYI5uouuaFa/HdyyOJP9knHGBMpiGjuNlDP
VhctUX2/qQsFUxCaChV7JSgm0Mnw==" />
Form contents
</form>
label_tag, text_field_tag, submit_tag
<%= form_tag("/search", method: "get") do %>
<%= label_tag(:q, "Search for:") %>
<%= text_field_tag(:q) %>
<%= submit_tag("Search") %>
<% end %>
<form accept-charset="UTF-8" action="/search" method="get">
<input name="utf8" type="hidden" value="&#x2713;" />
<label for="q">Search for:</label>
<input id="q" name="q" type="text" />
<input name="commit" type="submit" value="Search" />
</form>
Others input helpers
<%= password_field_tag(:password) %>
<%= hidden_field_tag(:parent_id, "5") %>
<%= number_field(:product, :price, in:
1.0..20.0, step: 0.5) %>
<input type="password" name="password" id="password" />
<input type="hidden" name="parent_id" id="parent_id"
value="5" />
<input step="0.5" min="1.0" max="20.0" type="number"
name="product[price]" id="product_price" />
search_field, telephone_field, date_field, datetime_field, datetime_local_field, month_field,
week_field, url_field, email_field, color_field, time_field, range_field
Form to an object
http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html
Setting up a form to an object
# routes
resources :developers
# controller
def new
@developer = Developer.new
end
# view
<%= form_for @developer do |f| %>
<%= f.text_field :name %><br>
<%= f.text_area :resume %><br>
<%= f.submit %>
<% end %>
<form class="new_developer" id="new_developer" action="/developers"
accept-charset="UTF-8" method="post">
<!-- autenticity_token and utf8 -->
<input type="text" name="developer[name]" id="developer_name" /><br>
<textarea name="developer[resume]" id="developer_resume">
</textarea><br>
<input type="submit" name="commit" value="Create Developer" />
</form>
Label
<%= f.label :name %><br>
<%= f.text_field :name %>
<label for="developer_name">Name</label><br>
<input type="text" name="developer[name]" id="developer_name" />
Error messages
# model
class Developer < ActiveRecord::Base
validates_presence_of :name
end
# view
<% if @developer.errors.any? %>
<ul>
<% @developer.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
<% end %>
<ul>
<li>Name can't be blank</li>
</ul>
Select
http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html
Select with array
<%= f.select(:gender, { M: 1, F: 2 },
{ include_blank: 'Choice' }) %>
<select name="developer[gender]" id="developer_gender">
<option value="">Choice</option>
<option selected="selected" value="1">M</option>
<option value="2">F</option>
</select>
<select name="developer[gender]" id="developer_gender">
<option selected="selected" value="1">M</option>
<option value="2">F</option>
</select>
<%= f.select(:gender, M: 1, F: 2) %>
Select with collection
<%= f.collection_select(:indication_id,
Developer.all, :id, :name,
{ prompt: 'None' }) %>
<select name="developer[indication_id]" id="
developer_indication_id">
<option value="">None</option>
<option value="1">Linus</option>
<option value="2">Bruno</option>
</select>
<select name="developer[indication_id]" id="
developer_indication_id">
<option value="1">Linus</option>
<option value="2">Bruno</option>
</select>
<%= f.collection_select(:indication_id,
Developer.all, :id, :name) %>
Customize fields
Select
<%= f.select(
:gender,
{ M: 1, F: 2 },
{ include_blank: 'Choice' },
{
class: 'css-class',
data: { id: 'gender', optional: true }
}
) %>
<select class="css-class" data-id="gender" data-
optional="true" name="developer[gender]" id="
developer_gender">
Nested forms
http://guides.rubyonrails.org/form_helpers.html#nested-forms
Configure model and controller
# controller
class DevelopersController < ApplicationController
def new
@developer = Developer.new
@developer.addresses.build
end
def developer_params
params.require(:developer).permit(:name, :resume, :
gender,
addresses_attributes: [:id, :name, :street])
end
end
# models
class Address < ActiveRecord::Base
belongs_to :developer
end
class Developer < ActiveRecord::Base
has_many :addresses
accepts_nested_attributes_for :addresses
end
Add nested form to view…
<%= form_for @developer do |f| %>
...
<%= f.fields_for :addresses do |addresses_form| %>
<%= addresses_form.text_field :name %>
<%= addresses_form.text_field :street %>
<% end %>
...
<% end %>
… renders
<input type="text" value="" name="developer[addresses_attributes][0][name]" id="
developer_addresses_attributes_0_name" />
<input type="text" value="" name="developer[addresses_attributes][0][street]" id="
developer_addresses_attributes_0_street" />
<input type="hidden" value="1" name="developer[addresses_attributes][0][id]" id="
developer_addresses_attributes_0_id" />
That's all folks
Bruno Almeida
https://github.com/wwwbruno
https://facebook.com/wwwbruno
https://twitter.com/@wwwbruno
http://www.slideshare.net/wwwbruno
Any questions?

Más contenido relacionado

La actualidad más candente

Https set up
Https set upHttps set up
Https set up
<svg> \">
 
Static Reference Analysis for GUI Objects in Android Software
Static Reference Analysis for GUI Objects in Android SoftwareStatic Reference Analysis for GUI Objects in Android Software
Static Reference Analysis for GUI Objects in Android Software
Dacong (Tony) Yan
 

La actualidad más candente (20)

Https set up
Https set upHttps set up
Https set up
 
Decompiladores
DecompiladoresDecompiladores
Decompiladores
 
Static Reference Analysis for GUI Objects in Android Software
Static Reference Analysis for GUI Objects in Android SoftwareStatic Reference Analysis for GUI Objects in Android Software
Static Reference Analysis for GUI Objects in Android Software
 
Introduction to UI Components in Magento 2
Introduction to UI Components in Magento 2Introduction to UI Components in Magento 2
Introduction to UI Components in Magento 2
 
Magento 2 UI Components Overview
Magento 2 UI Components OverviewMagento 2 UI Components Overview
Magento 2 UI Components Overview
 
Modules and injector
Modules and injectorModules and injector
Modules and injector
 
23. CodeIgniter sessions
23. CodeIgniter sessions23. CodeIgniter sessions
23. CodeIgniter sessions
 
Security in laravel
Security in laravelSecurity in laravel
Security in laravel
 
Binary Studio Academy 2016: Laravel Controllers
Binary Studio Academy 2016: Laravel ControllersBinary Studio Academy 2016: Laravel Controllers
Binary Studio Academy 2016: Laravel Controllers
 
Confluence - Improving Space Navigation. London AUG October 2013
Confluence - Improving Space Navigation. London AUG October 2013Confluence - Improving Space Navigation. London AUG October 2013
Confluence - Improving Space Navigation. London AUG October 2013
 
Support Design Library
Support Design LibrarySupport Design Library
Support Design Library
 
Droidcon Moscow 2015. Support Design Library. Григорий Джанелидзе - e-Legion
Droidcon Moscow 2015. Support Design Library. Григорий Джанелидзе - e-LegionDroidcon Moscow 2015. Support Design Library. Григорий Джанелидзе - e-Legion
Droidcon Moscow 2015. Support Design Library. Григорий Джанелидзе - e-Legion
 
AngularJs - Part 3
AngularJs - Part 3AngularJs - Part 3
AngularJs - Part 3
 
5. hello popescu
5. hello popescu5. hello popescu
5. hello popescu
 
날로 먹는 Django admin 활용
날로 먹는 Django admin 활용날로 먹는 Django admin 활용
날로 먹는 Django admin 활용
 
jQuery 實戰經驗講座
jQuery 實戰經驗講座jQuery 實戰經驗講座
jQuery 實戰經驗講座
 
Laravel 로 배우는 서버사이드 #5
Laravel 로 배우는 서버사이드 #5Laravel 로 배우는 서버사이드 #5
Laravel 로 배우는 서버사이드 #5
 
Building scalable products with WordPress - WordCamp London 2018
Building scalable products with WordPress - WordCamp London 2018Building scalable products with WordPress - WordCamp London 2018
Building scalable products with WordPress - WordCamp London 2018
 
Lo nuevo de Django 1.7 y 1.8
Lo nuevo de Django 1.7 y 1.8Lo nuevo de Django 1.7 y 1.8
Lo nuevo de Django 1.7 y 1.8
 
Stole16
Stole16Stole16
Stole16
 

Destacado

чуло вида
чуло видачуло вида
чуло вида
Maja Simic
 
การประเมินการอ่าน คิดวิเคราะห์ และเขียน
การประเมินการอ่าน คิดวิเคราะห์ และเขียนการประเมินการอ่าน คิดวิเคราะห์ และเขียน
การประเมินการอ่าน คิดวิเคราะห์ และเขียน
krupornpana55
 
Portable network graphics
Portable network graphicsPortable network graphics
Portable network graphics
Esty Swandana
 

Destacado (19)

Brincando com FFI no Ruby
Brincando com FFI no RubyBrincando com FFI no Ruby
Brincando com FFI no Ruby
 
Git - Workshop Disruptiva
Git - Workshop DisruptivaGit - Workshop Disruptiva
Git - Workshop Disruptiva
 
RubyMotion: Put your Dreams in Motion with Ruby
RubyMotion: Put your Dreams in Motion with RubyRubyMotion: Put your Dreams in Motion with Ruby
RubyMotion: Put your Dreams in Motion with Ruby
 
Concurrency in Ruby
Concurrency in RubyConcurrency in Ruby
Concurrency in Ruby
 
ניטור ומחקר וידיאו באינטרנט
ניטור ומחקר וידיאו באינטרנטניטור ומחקר וידיאו באינטרנט
ניטור ומחקר וידיאו באינטרנט
 
Ad Design - Galaxy Gala
Ad Design - Galaxy GalaAd Design - Galaxy Gala
Ad Design - Galaxy Gala
 
Mir datasheet
Mir datasheetMir datasheet
Mir datasheet
 
3
33
3
 
Iсторичнi аспекти соцiалiзацii...
Iсторичнi аспекти соцiалiзацii...Iсторичнi аспекти соцiалiзацii...
Iсторичнi аспекти соцiалiзацii...
 
Austcoast
AustcoastAustcoast
Austcoast
 
чуло вида
чуло видачуло вида
чуло вида
 
Ons Wadden Gebied
Ons Wadden GebiedOns Wadden Gebied
Ons Wadden Gebied
 
Ioug oow12 em12c
Ioug oow12 em12cIoug oow12 em12c
Ioug oow12 em12c
 
การประเมินการอ่าน คิดวิเคราะห์ และเขียน
การประเมินการอ่าน คิดวิเคราะห์ และเขียนการประเมินการอ่าน คิดวิเคราะห์ และเขียน
การประเมินการอ่าน คิดวิเคราะห์ และเขียน
 
Trabajo unidad 3
Trabajo unidad 3Trabajo unidad 3
Trabajo unidad 3
 
Where is Wally - user study af Bettina Ridler og Helle Mortensen, GN Netcom
Where is Wally - user study af Bettina Ridler og Helle Mortensen, GN NetcomWhere is Wally - user study af Bettina Ridler og Helle Mortensen, GN Netcom
Where is Wally - user study af Bettina Ridler og Helle Mortensen, GN Netcom
 
Ch 1 organization of construction projects
Ch 1 organization of construction projectsCh 1 organization of construction projects
Ch 1 organization of construction projects
 
Automatiseret GUI-test af Lars Kjølholm, BRF Kredit
Automatiseret GUI-test af Lars Kjølholm, BRF KreditAutomatiseret GUI-test af Lars Kjølholm, BRF Kredit
Automatiseret GUI-test af Lars Kjølholm, BRF Kredit
 
Portable network graphics
Portable network graphicsPortable network graphics
Portable network graphics
 

Similar a Understanding form helpers

Action View Form Helpers - 1, Season 2
Action View Form Helpers - 1, Season 2Action View Form Helpers - 1, Season 2
Action View Form Helpers - 1, Season 2
RORLAB
 
Action View Form Helpers - 2, Season 2
Action View Form Helpers - 2, Season 2Action View Form Helpers - 2, Season 2
Action View Form Helpers - 2, Season 2
RORLAB
 
Desenvolvimento web com Ruby on Rails (parte 4)
Desenvolvimento web com Ruby on Rails (parte 4)Desenvolvimento web com Ruby on Rails (parte 4)
Desenvolvimento web com Ruby on Rails (parte 4)
Joao Lucas Santana
 
How to create a magento controller in magento extension
How to create a magento controller in magento extensionHow to create a magento controller in magento extension
How to create a magento controller in magento extension
Hendy Irawan
 
Open Selector
Open SelectorOpen Selector
Open Selector
jjdelc
 
Private slideshow
Private slideshowPrivate slideshow
Private slideshow
sblackman
 

Similar a Understanding form helpers (20)

Action View Form Helpers - 1, Season 2
Action View Form Helpers - 1, Season 2Action View Form Helpers - 1, Season 2
Action View Form Helpers - 1, Season 2
 
Action View Form Helpers - 2, Season 2
Action View Form Helpers - 2, Season 2Action View Form Helpers - 2, Season 2
Action View Form Helpers - 2, Season 2
 
Intro to Jinja2 Templates - San Francisco Flask Meetup
Intro to Jinja2 Templates - San Francisco Flask MeetupIntro to Jinja2 Templates - San Francisco Flask Meetup
Intro to Jinja2 Templates - San Francisco Flask Meetup
 
How to Create A Magento Adminhtml Controller in Magento Extension
How to Create A Magento Adminhtml Controller in Magento ExtensionHow to Create A Magento Adminhtml Controller in Magento Extension
How to Create A Magento Adminhtml Controller in Magento Extension
 
04 Html Form Get Post Login System
04 Html Form Get Post Login System04 Html Form Get Post Login System
04 Html Form Get Post Login System
 
jQuery Mobile Introduction ( demo on EZoapp )
jQuery Mobile Introduction ( demo on EZoapp )jQuery Mobile Introduction ( demo on EZoapp )
jQuery Mobile Introduction ( demo on EZoapp )
 
Jinja2 Templates - San Francisco Flask Meetup
Jinja2 Templates - San Francisco Flask MeetupJinja2 Templates - San Francisco Flask Meetup
Jinja2 Templates - San Francisco Flask Meetup
 
Nagios Conference 2014 - Troy Lea - JavaScript and jQuery - Nagios XI Tips, T...
Nagios Conference 2014 - Troy Lea - JavaScript and jQuery - Nagios XI Tips, T...Nagios Conference 2014 - Troy Lea - JavaScript and jQuery - Nagios XI Tips, T...
Nagios Conference 2014 - Troy Lea - JavaScript and jQuery - Nagios XI Tips, T...
 
QCon 2015 - Thinking in components: A new paradigm for Web UI
QCon 2015 - Thinking in components: A new paradigm for Web UIQCon 2015 - Thinking in components: A new paradigm for Web UI
QCon 2015 - Thinking in components: A new paradigm for Web UI
 
Desenvolvimento web com Ruby on Rails (parte 4)
Desenvolvimento web com Ruby on Rails (parte 4)Desenvolvimento web com Ruby on Rails (parte 4)
Desenvolvimento web com Ruby on Rails (parte 4)
 
How to create a magento controller in magento extension
How to create a magento controller in magento extensionHow to create a magento controller in magento extension
How to create a magento controller in magento extension
 
Alfredo-PUMEX
Alfredo-PUMEXAlfredo-PUMEX
Alfredo-PUMEX
 
Alfredo-PUMEX
Alfredo-PUMEXAlfredo-PUMEX
Alfredo-PUMEX
 
Alfredo-PUMEX
Alfredo-PUMEXAlfredo-PUMEX
Alfredo-PUMEX
 
Alfredo-PUMEX
Alfredo-PUMEXAlfredo-PUMEX
Alfredo-PUMEX
 
Getting started with Rails (4), Season 2
Getting started with Rails (4), Season 2Getting started with Rails (4), Season 2
Getting started with Rails (4), Season 2
 
Open Selector
Open SelectorOpen Selector
Open Selector
 
HTML::FormFu talk for Sydney PM
HTML::FormFu talk for Sydney PMHTML::FormFu talk for Sydney PM
HTML::FormFu talk for Sydney PM
 
Private slideshow
Private slideshowPrivate slideshow
Private slideshow
 
Pengenalan AngularJS
Pengenalan AngularJSPengenalan AngularJS
Pengenalan AngularJS
 

Último

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Último (20)

Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 

Understanding form helpers

  • 2. ● Form tag ● Form to an object ● Select ● Customize fields ● Nested forms
  • 5. form_tag <%= form_tag do %> Form contents <% end %> <form action="/" accept-charset="UTF-8" method="post"> <input name="utf8" type="hidden" value="&#x2713;" /> <input type="hidden" name="authenticity_token" value=" jzi1o/1Wl8yTZ2e1Z3QE99BFYI5uouuaFa/HdyyOJP9knHGBMpiGjuNlDP VhctUX2/qQsFUxCaChV7JSgm0Mnw==" /> Form contents </form>
  • 6. label_tag, text_field_tag, submit_tag <%= form_tag("/search", method: "get") do %> <%= label_tag(:q, "Search for:") %> <%= text_field_tag(:q) %> <%= submit_tag("Search") %> <% end %> <form accept-charset="UTF-8" action="/search" method="get"> <input name="utf8" type="hidden" value="&#x2713;" /> <label for="q">Search for:</label> <input id="q" name="q" type="text" /> <input name="commit" type="submit" value="Search" /> </form>
  • 7. Others input helpers <%= password_field_tag(:password) %> <%= hidden_field_tag(:parent_id, "5") %> <%= number_field(:product, :price, in: 1.0..20.0, step: 0.5) %> <input type="password" name="password" id="password" /> <input type="hidden" name="parent_id" id="parent_id" value="5" /> <input step="0.5" min="1.0" max="20.0" type="number" name="product[price]" id="product_price" /> search_field, telephone_field, date_field, datetime_field, datetime_local_field, month_field, week_field, url_field, email_field, color_field, time_field, range_field
  • 8. Form to an object http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html
  • 9. Setting up a form to an object # routes resources :developers # controller def new @developer = Developer.new end # view <%= form_for @developer do |f| %> <%= f.text_field :name %><br> <%= f.text_area :resume %><br> <%= f.submit %> <% end %> <form class="new_developer" id="new_developer" action="/developers" accept-charset="UTF-8" method="post"> <!-- autenticity_token and utf8 --> <input type="text" name="developer[name]" id="developer_name" /><br> <textarea name="developer[resume]" id="developer_resume"> </textarea><br> <input type="submit" name="commit" value="Create Developer" /> </form>
  • 10. Label <%= f.label :name %><br> <%= f.text_field :name %> <label for="developer_name">Name</label><br> <input type="text" name="developer[name]" id="developer_name" />
  • 11. Error messages # model class Developer < ActiveRecord::Base validates_presence_of :name end # view <% if @developer.errors.any? %> <ul> <% @developer.errors.full_messages.each do |msg| %> <li><%= msg %></li> <% end %> </ul> <% end %> <ul> <li>Name can't be blank</li> </ul>
  • 13. Select with array <%= f.select(:gender, { M: 1, F: 2 }, { include_blank: 'Choice' }) %> <select name="developer[gender]" id="developer_gender"> <option value="">Choice</option> <option selected="selected" value="1">M</option> <option value="2">F</option> </select> <select name="developer[gender]" id="developer_gender"> <option selected="selected" value="1">M</option> <option value="2">F</option> </select> <%= f.select(:gender, M: 1, F: 2) %>
  • 14. Select with collection <%= f.collection_select(:indication_id, Developer.all, :id, :name, { prompt: 'None' }) %> <select name="developer[indication_id]" id=" developer_indication_id"> <option value="">None</option> <option value="1">Linus</option> <option value="2">Bruno</option> </select> <select name="developer[indication_id]" id=" developer_indication_id"> <option value="1">Linus</option> <option value="2">Bruno</option> </select> <%= f.collection_select(:indication_id, Developer.all, :id, :name) %>
  • 16. Select <%= f.select( :gender, { M: 1, F: 2 }, { include_blank: 'Choice' }, { class: 'css-class', data: { id: 'gender', optional: true } } ) %> <select class="css-class" data-id="gender" data- optional="true" name="developer[gender]" id=" developer_gender">
  • 18. Configure model and controller # controller class DevelopersController < ApplicationController def new @developer = Developer.new @developer.addresses.build end def developer_params params.require(:developer).permit(:name, :resume, : gender, addresses_attributes: [:id, :name, :street]) end end # models class Address < ActiveRecord::Base belongs_to :developer end class Developer < ActiveRecord::Base has_many :addresses accepts_nested_attributes_for :addresses end
  • 19. Add nested form to view… <%= form_for @developer do |f| %> ... <%= f.fields_for :addresses do |addresses_form| %> <%= addresses_form.text_field :name %> <%= addresses_form.text_field :street %> <% end %> ... <% end %>
  • 20. … renders <input type="text" value="" name="developer[addresses_attributes][0][name]" id=" developer_addresses_attributes_0_name" /> <input type="text" value="" name="developer[addresses_attributes][0][street]" id=" developer_addresses_attributes_0_street" /> <input type="hidden" value="1" name="developer[addresses_attributes][0][id]" id=" developer_addresses_attributes_0_id" />
  • 21. That's all folks Bruno Almeida https://github.com/wwwbruno https://facebook.com/wwwbruno https://twitter.com/@wwwbruno http://www.slideshare.net/wwwbruno Any questions?