SlideShare une entreprise Scribd logo
1  sur  21
Télécharger pour lire hors ligne
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?

Contenu connexe

Tendances

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
 

Tendances (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
 

En vedette

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

En vedette (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
 

Similaire à 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
 

Similaire à 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
 

Dernier

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Dernier (20)

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
AI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by Anitaraj
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
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
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 

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?