SlideShare a Scribd company logo
1 of 32
Download to read offline
Ror lab. season 2
   - the 13th round -



  Action View
Form Helpers - 1

   December 29th, 2012

     Hyoseong Choi
form_tag
• Two arguments
 1. path for action : absolutely 1st argument
 2. options hash
   • HTTP method
     : post(default), get, put, delete

   • HTML options : class, style, ...
form_tag
                      Basic Form

<%= form_tag do %>
  Form contents
<% end %>
                                          app/views/home/index.html.erb

                                        current action

<form accept-charset="UTF-8" action="/home/index" method="post">
  <div style="margin:0;padding:0">
    <input name="utf8" type="hidden" value="&#x2713;" />
    <input name="authenticity_token" type="hidden"
value="f755bb0ed134b76c432144748a6d4b7a7ddf2b71" />
  </div>
  Form contents                      to prevent
</form>                                CSRF
form_tag
              Multiple Hashes

form_tag(:controller => "people", :action =>
"search", :method => "get", :class => "nifty_form")

# => '<form accept-charset="UTF-8" action="/people/
search?method=get&class=nifty_form" method="post">'




form_tag({:controller => "people", :action =>
"search"}, :method => "get", :class => "nifty_form")

# => '<form accept-charset="UTF-8" action="/people/
search" method="get" class="nifty_form">'
Helpers
            Generating Form Elements
• text_field_tag
• text_area_tag                                 http://modernizr.com/docs/
• check_box_tag                                    Modernizr
• radio_button_tag                                  yepnope
• password_field_tag
• hidden_field_tag                                   polyfiller
• search_field_tag
• telephone_field_tag                           HTML5 controls
• url_field_tag
• email_field_tag
http://en.wikipedia.org/wiki/Polyfill
https://github.com/russfrisch/modernizr-rails
http://html5readiness.com
HTML 5 “Form 2.0”
Firefox v17.0.1        Safari v6.0.2




Chrome v23.0.1271.97   Opera v12.11
HTML 5 “Form 2.0”
         Form Element Helpers
     Rails 3              HTML5 Input Types
   search_field                      search
  telephone_field                      tel
     url_field                         url
    email_field                       email
   number_field                     number
    range_field                      range
                   Agile Web Development with Rails 4th edition
HTML 5 “Form 2.0”
Firefox v17.0.1        Safari v6.0.2




Chrome v23.0.1271.97   Opera v12.11
Search Form
                                  for bookmark

<%= 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">
  <label for="q">Search for:</label>
  <input id="q" name="q" type="text" />
  <input name="commit" type="submit" value="Search" />
</form>
Form Elements Helpers
 Checkboxes
 <%=   check_box_tag(:pet_dog) %>
 <%=   label_tag(:pet_dog, "I own a dog") %>
 <%=   check_box_tag(:pet_cat) %>
 <%=   label_tag(:pet_cat, "I own a cat") %>




 <input id="pet_dog" name="pet_dog" type="checkbox"
 value="1" />
 <label for="pet_dog">I own a dog</label>
 <input id="pet_cat" name="pet_cat" type="checkbox"
 value="1" />
 <label for="pet_cat">I own a cat</label>
Form Elements Helpers
 Radio Buttons
 <%=   radio_button_tag(:age, "child") %>
 <%=   label_tag(:age_child, "I am younger than 21") %>
 <%=   radio_button_tag(:age, "adult") %>
 <%=   label_tag(:age_adult, "I'm over 21") %>




 <input id="age_child" name="age" type="radio"
 value="child" />
 <label for="age_child">I am younger than 21</label>
 <input id="age_adult" name="age" type="radio"
 value="adult" />
 <label for="age_adult">I'm over 21</label>
Form Elements Helpers
 Others
 <input id="age_child" name="age" type="radio"
 value="child" />
 <label for="age_child">I am younger than 21</label>
 <input id="age_adult" name="age" type="radio"
 value="adult" />
 <label for="age_adult">I'm over 21</label>




 <input id="age_child" name="age" type="radio"
 value="child" />
 <label for="age_child">I am younger than 21</label>
 <input id="age_adult" name="age" type="radio"
 value="adult" />
 <label for="age_adult">I'm over 21</label>
Model Object
      Helpers

            • check_box_tag
            • radio_button_tag
• No _tag   • text_area_tag
            • password_field_tag
            • hidden_field_tag
for Model Object
        @person -> name : “Henry”


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

              for an instance   for a method
                  variable       name(attr.)




<input id="person_name" name="person[name]"
type="text" value="Henry"/>
Binding a Form to
    an Object
def new
  @article = Article.new
end




<%= 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 %>
<%= 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 %>




<form accept-charset="UTF-8" action="/articles/
create" method="post" class="nifty_form">
  <input id="article_title" name="article[title]"
size="30" type="text" />
  <textarea id="article_body" name="article[body]"
cols="60" rows="12"></textarea>
  <input name="commit" type="submit" value="Create" /
>
</form>
in the controller,


params[:article]
params[:article][:title]
params[:article][:body]
fields_for
Person
  •name
  •age
  •sex
  •address
  •telephone
fields_for
             has_one
                or
Person                       Contact
            has_many
  •name                       •address
  •age                        •telephone
  •sex
            belong_to

          using nested attributes
fields_for

class Person < ActiveRecord::Base
  has_one :contact, :dependent => :destroy
end

class Contact < ActiveRecord::Base
  belongs_to :person
end




        using accepts_nested_attributes_for
Using Resources
  resources :articles in config/routes.rb


## Creating a new article
# long-style:
form_for(@article, :url => articles_path)
# short-style (record identification gets used):
form_for(@article)



## Editing an existing article
# long-style:
form_for(@article, :url =>
article_path(@article), :html => { :method =>
"put" })
# short-style:
form_for(@article)
Using Namespaces
namespace :admin do
  resources :posts, :comments
end
                                                   in routes.rb


form_for [:admin, @post]
                                               in _form.html.erb

admin_post_path(@post) on update
app/controllers/admin/posts_controller.rb
app/controllers/admin/comments_controller.rb
app/views/admin/posts/new.html.erb
app/views/admin/posts/edit.html.erb
HTTP Verbs

• GET
           for all browsers
• POST
• PUT             ?
• DELETE
PUT & DELETE
       • A hidden input : _method
form_tag(search_path, :method => "put")




<form accept-charset="UTF-8" action="/search"
method="post">
  <div style="margin:0;padding:0">
    <input name="_method" type="hidden" value="put" />
    <input name="utf8" type="hidden" value="&#x2713;" />
    <input name="authenticity_token" type="hidden"
value="f755bb0ed134b76c432144748a6d4b7a7ddf2b71" />
  </div>
  ...
select_tag
<select name="city_id" id="city_id">
  <option value="1">Lisbon</option>
  <option value="2">Madrid</option>
  ...
  <option value="12">Berlin</option>
</select>




<%= select_tag(:city_id, '<option value="1">Lisbon</
option>...') %>
options_for_select
 <%= options_for_select([['Lisbon', 1], ['Madrid',
 2], ...]) %>
                      1st argument => a nested array
 output:
  
 <option value="1">Lisbon</option>
 <option value="2">Madrid</option>
 ...




 <%= select_tag(:city_id, options_for_select(...)) %>
options_for_select
 <%= options_for_select([['Lisbon', 1], ['Madrid',
 2], ...], 2) %>
  
 output:      2nd argument => ‘selected’
  
 <option value="1">Lisbon</option>
 <option value="2" selected="selected">Madrid</option>
select for ORM
               # controller:
               @person = Person.new(:city_id => 2)




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




                                      pre-selected by Rails
               # select on a form builder
               <%= f.select(:city_id, ...) %>
select from
          collection
 <% cities_array = City.all.map { |city| [city.name,
 city.id] } %>
 <%= options_for_select(cities_array) %>




in short form,
   options_from_collection
                      (City.all, :id, :name)
collection_select

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


                         or
    f.
<%= f.collection_select
    (:city_id, City.all, :id, :name) %>
감사합니다.

More Related Content

What's hot

Django Forms: Best Practices, Tips, Tricks
Django Forms: Best Practices, Tips, TricksDjango Forms: Best Practices, Tips, Tricks
Django Forms: Best Practices, Tips, TricksShawn Rider
 
Connecting Content Silos: One CMS, Many Sites With The WordPress REST API
 Connecting Content Silos: One CMS, Many Sites With The WordPress REST API Connecting Content Silos: One CMS, Many Sites With The WordPress REST API
Connecting Content Silos: One CMS, Many Sites With The WordPress REST APICaldera Labs
 
Flask patterns
Flask patternsFlask patterns
Flask patternsit-people
 
Hyperproductive JSF 2.0 @ JavaOne Brazil 2010
Hyperproductive JSF 2.0 @ JavaOne Brazil 2010Hyperproductive JSF 2.0 @ JavaOne Brazil 2010
Hyperproductive JSF 2.0 @ JavaOne Brazil 2010Arun Gupta
 
Using Geeklog as a Web Application Framework
Using Geeklog as a Web Application FrameworkUsing Geeklog as a Web Application Framework
Using Geeklog as a Web Application FrameworkDirk Haun
 
Basic Crud In Django
Basic Crud In DjangoBasic Crud In Django
Basic Crud In Djangomcantelon
 
Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5Elena Kolevska
 
Service approach for development Rest API in Symfony2
Service approach for development Rest API in Symfony2Service approach for development Rest API in Symfony2
Service approach for development Rest API in Symfony2Sumy PHP User Grpoup
 
Zend - Installation And Sample Project Creation
Zend - Installation And Sample Project Creation Zend - Installation And Sample Project Creation
Zend - Installation And Sample Project Creation Compare Infobase Limited
 
What's new in Rails 2?
What's new in Rails 2?What's new in Rails 2?
What's new in Rails 2?brynary
 
Flask - Backend com Python - Semcomp 18
Flask - Backend com Python - Semcomp 18Flask - Backend com Python - Semcomp 18
Flask - Backend com Python - Semcomp 18Lar21
 
Service approach for development REST API in Symfony2
Service approach for development REST API in Symfony2Service approach for development REST API in Symfony2
Service approach for development REST API in Symfony2Sumy PHP User Grpoup
 
Filling the flask
Filling the flaskFilling the flask
Filling the flaskJason Myers
 
Single Page Web Apps As WordPress Admin Interfaces Using AngularJS & The Word...
Single Page Web Apps As WordPress Admin Interfaces Using AngularJS & The Word...Single Page Web Apps As WordPress Admin Interfaces Using AngularJS & The Word...
Single Page Web Apps As WordPress Admin Interfaces Using AngularJS & The Word...Caldera Labs
 
Caldera Learn - LoopConf WP API + Angular FTW Workshop
Caldera Learn - LoopConf WP API + Angular FTW WorkshopCaldera Learn - LoopConf WP API + Angular FTW Workshop
Caldera Learn - LoopConf WP API + Angular FTW WorkshopCalderaLearn
 
ActiveResource & REST
ActiveResource & RESTActiveResource & REST
ActiveResource & RESTRobbert
 

What's hot (20)

Django Forms: Best Practices, Tips, Tricks
Django Forms: Best Practices, Tips, TricksDjango Forms: Best Practices, Tips, Tricks
Django Forms: Best Practices, Tips, Tricks
 
Connecting Content Silos: One CMS, Many Sites With The WordPress REST API
 Connecting Content Silos: One CMS, Many Sites With The WordPress REST API Connecting Content Silos: One CMS, Many Sites With The WordPress REST API
Connecting Content Silos: One CMS, Many Sites With The WordPress REST API
 
Flask patterns
Flask patternsFlask patterns
Flask patterns
 
Kyiv.py #17 Flask talk
Kyiv.py #17 Flask talkKyiv.py #17 Flask talk
Kyiv.py #17 Flask talk
 
Hyperproductive JSF 2.0 @ JavaOne Brazil 2010
Hyperproductive JSF 2.0 @ JavaOne Brazil 2010Hyperproductive JSF 2.0 @ JavaOne Brazil 2010
Hyperproductive JSF 2.0 @ JavaOne Brazil 2010
 
Rails 4.0
Rails 4.0Rails 4.0
Rails 4.0
 
Using Geeklog as a Web Application Framework
Using Geeklog as a Web Application FrameworkUsing Geeklog as a Web Application Framework
Using Geeklog as a Web Application Framework
 
Basic Crud In Django
Basic Crud In DjangoBasic Crud In Django
Basic Crud In Django
 
Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5
 
Service approach for development Rest API in Symfony2
Service approach for development Rest API in Symfony2Service approach for development Rest API in Symfony2
Service approach for development Rest API in Symfony2
 
Zend - Installation And Sample Project Creation
Zend - Installation And Sample Project Creation Zend - Installation And Sample Project Creation
Zend - Installation And Sample Project Creation
 
What's new in Rails 2?
What's new in Rails 2?What's new in Rails 2?
What's new in Rails 2?
 
Flask - Backend com Python - Semcomp 18
Flask - Backend com Python - Semcomp 18Flask - Backend com Python - Semcomp 18
Flask - Backend com Python - Semcomp 18
 
Zend framework
Zend frameworkZend framework
Zend framework
 
Service approach for development REST API in Symfony2
Service approach for development REST API in Symfony2Service approach for development REST API in Symfony2
Service approach for development REST API in Symfony2
 
Filling the flask
Filling the flaskFilling the flask
Filling the flask
 
Single Page Web Apps As WordPress Admin Interfaces Using AngularJS & The Word...
Single Page Web Apps As WordPress Admin Interfaces Using AngularJS & The Word...Single Page Web Apps As WordPress Admin Interfaces Using AngularJS & The Word...
Single Page Web Apps As WordPress Admin Interfaces Using AngularJS & The Word...
 
Caldera Learn - LoopConf WP API + Angular FTW Workshop
Caldera Learn - LoopConf WP API + Angular FTW WorkshopCaldera Learn - LoopConf WP API + Angular FTW Workshop
Caldera Learn - LoopConf WP API + Angular FTW Workshop
 
ActiveResource & REST
ActiveResource & RESTActiveResource & REST
ActiveResource & REST
 
BDD with cucumber
BDD with cucumberBDD with cucumber
BDD with cucumber
 

Similar to 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 2RORLAB
 
Acceptance Testing with Webrat
Acceptance Testing with WebratAcceptance Testing with Webrat
Acceptance Testing with WebratLuismi Cavallé
 
Your Custom WordPress Admin Pages Suck
Your Custom WordPress Admin Pages SuckYour Custom WordPress Admin Pages Suck
Your Custom WordPress Admin Pages SuckAnthony Montalbano
 
Understanding form helpers
Understanding form helpersUnderstanding form helpers
Understanding form helpersBruno Almeida
 
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 2RORLAB
 
HTML5 New and Improved
HTML5   New and ImprovedHTML5   New and Improved
HTML5 New and ImprovedTimothy Fisher
 
Active Record Form Helpers, Season 1
Active Record Form Helpers, Season 1Active Record Form Helpers, Season 1
Active Record Form Helpers, Season 1RORLAB
 
The project gutenberg e book, fairy tales from brazil, by elsie spicer
The project gutenberg e book, fairy tales from brazil, by elsie spicerThe project gutenberg e book, fairy tales from brazil, by elsie spicer
The project gutenberg e book, fairy tales from brazil, by elsie spicerAndrei Hortúa
 
HTML5 and the dawn of rich mobile web applications pt 2
HTML5 and the dawn of rich mobile web applications pt 2HTML5 and the dawn of rich mobile web applications pt 2
HTML5 and the dawn of rich mobile web applications pt 2James Pearce
 
Rugalytics | Ruby Manor Nov 2008
Rugalytics | Ruby Manor Nov 2008Rugalytics | Ruby Manor Nov 2008
Rugalytics | Ruby Manor Nov 2008Rob
 
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 UIOliver Häger
 
Implementation of GUI Framework part3
Implementation of GUI Framework part3Implementation of GUI Framework part3
Implementation of GUI Framework part3masahiroookubo
 
Django - Framework web para perfeccionistas com prazos
Django - Framework web para perfeccionistas com prazosDjango - Framework web para perfeccionistas com prazos
Django - Framework web para perfeccionistas com prazosIgor Sobreira
 
Practical PHP by example Jan Leth-Kjaer
Practical PHP by example   Jan Leth-KjaerPractical PHP by example   Jan Leth-Kjaer
Practical PHP by example Jan Leth-KjaerCOMMON Europe
 
Improving state of M2 front-end - Magento 2 Community Project
Improving state of M2 front-end - Magento 2 Community ProjectImproving state of M2 front-end - Magento 2 Community Project
Improving state of M2 front-end - Magento 2 Community ProjectBartek Igielski
 

Similar to Action View Form Helpers - 1, Season 2 (20)

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
 
Acceptance Testing with Webrat
Acceptance Testing with WebratAcceptance Testing with Webrat
Acceptance Testing with Webrat
 
Your Custom WordPress Admin Pages Suck
Your Custom WordPress Admin Pages SuckYour Custom WordPress Admin Pages Suck
Your Custom WordPress Admin Pages Suck
 
Introduction to Html5
Introduction to Html5Introduction to Html5
Introduction to Html5
 
Rails <form> Chronicle
Rails <form> ChronicleRails <form> Chronicle
Rails <form> Chronicle
 
Understanding form helpers
Understanding form helpersUnderstanding form helpers
Understanding form helpers
 
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
 
JSP
JSPJSP
JSP
 
HTML5 New and Improved
HTML5   New and ImprovedHTML5   New and Improved
HTML5 New and Improved
 
Wicket 2010
Wicket 2010Wicket 2010
Wicket 2010
 
Active Record Form Helpers, Season 1
Active Record Form Helpers, Season 1Active Record Form Helpers, Season 1
Active Record Form Helpers, Season 1
 
The project gutenberg e book, fairy tales from brazil, by elsie spicer
The project gutenberg e book, fairy tales from brazil, by elsie spicerThe project gutenberg e book, fairy tales from brazil, by elsie spicer
The project gutenberg e book, fairy tales from brazil, by elsie spicer
 
HTML5 and the dawn of rich mobile web applications pt 2
HTML5 and the dawn of rich mobile web applications pt 2HTML5 and the dawn of rich mobile web applications pt 2
HTML5 and the dawn of rich mobile web applications pt 2
 
Rugalytics | Ruby Manor Nov 2008
Rugalytics | Ruby Manor Nov 2008Rugalytics | Ruby Manor Nov 2008
Rugalytics | Ruby Manor Nov 2008
 
Mobile themes, QR codes, and shortURLs
Mobile themes, QR codes, and shortURLsMobile themes, QR codes, and shortURLs
Mobile themes, QR codes, and shortURLs
 
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
 
Implementation of GUI Framework part3
Implementation of GUI Framework part3Implementation of GUI Framework part3
Implementation of GUI Framework part3
 
Django - Framework web para perfeccionistas com prazos
Django - Framework web para perfeccionistas com prazosDjango - Framework web para perfeccionistas com prazos
Django - Framework web para perfeccionistas com prazos
 
Practical PHP by example Jan Leth-Kjaer
Practical PHP by example   Jan Leth-KjaerPractical PHP by example   Jan Leth-Kjaer
Practical PHP by example Jan Leth-Kjaer
 
Improving state of M2 front-end - Magento 2 Community Project
Improving state of M2 front-end - Magento 2 Community ProjectImproving state of M2 front-end - Magento 2 Community Project
Improving state of M2 front-end - Magento 2 Community Project
 

More from RORLAB

Getting Started with Rails (4)
Getting Started with Rails (4) Getting Started with Rails (4)
Getting Started with Rails (4) RORLAB
 
Getting Started with Rails (3)
Getting Started with Rails (3) Getting Started with Rails (3)
Getting Started with Rails (3) RORLAB
 
Getting Started with Rails (2)
Getting Started with Rails (2)Getting Started with Rails (2)
Getting Started with Rails (2)RORLAB
 
Getting Started with Rails (1)
Getting Started with Rails (1)Getting Started with Rails (1)
Getting Started with Rails (1)RORLAB
 
Self join in active record association
Self join in active record associationSelf join in active record association
Self join in active record associationRORLAB
 
Asset Pipeline in Ruby on Rails
Asset Pipeline in Ruby on RailsAsset Pipeline in Ruby on Rails
Asset Pipeline in Ruby on RailsRORLAB
 
레일스가이드 한글번역 공개프로젝트 RORLabGuides 소개
레일스가이드 한글번역 공개프로젝트 RORLabGuides 소개레일스가이드 한글번역 공개프로젝트 RORLabGuides 소개
레일스가이드 한글번역 공개프로젝트 RORLabGuides 소개RORLAB
 
Active Support Core Extension (3)
Active Support Core Extension (3)Active Support Core Extension (3)
Active Support Core Extension (3)RORLAB
 
Active Support Core Extension (2)
Active Support Core Extension (2)Active Support Core Extension (2)
Active Support Core Extension (2)RORLAB
 
Active Support Core Extensions (1)
Active Support Core Extensions (1)Active Support Core Extensions (1)
Active Support Core Extensions (1)RORLAB
 
ActiveRecord Query Interface (2), Season 2
ActiveRecord Query Interface (2), Season 2ActiveRecord Query Interface (2), Season 2
ActiveRecord Query Interface (2), Season 2RORLAB
 
Active Record Query Interface (1), Season 2
Active Record Query Interface (1), Season 2Active Record Query Interface (1), Season 2
Active Record Query Interface (1), Season 2RORLAB
 
Active Record Association (2), Season 2
Active Record Association (2), Season 2Active Record Association (2), Season 2
Active Record Association (2), Season 2RORLAB
 
ActiveRecord Association (1), Season 2
ActiveRecord Association (1), Season 2ActiveRecord Association (1), Season 2
ActiveRecord Association (1), Season 2RORLAB
 
ActiveRecord Callbacks & Observers, Season 2
ActiveRecord Callbacks & Observers, Season 2ActiveRecord Callbacks & Observers, Season 2
ActiveRecord Callbacks & Observers, Season 2RORLAB
 
ActiveRecord Validations, Season 2
ActiveRecord Validations, Season 2ActiveRecord Validations, Season 2
ActiveRecord Validations, Season 2RORLAB
 
Rails Database Migration, Season 2
Rails Database Migration, Season 2Rails Database Migration, Season 2
Rails Database Migration, Season 2RORLAB
 
Getting started with Rails (3), Season 2
Getting started with Rails (3), Season 2Getting started with Rails (3), Season 2
Getting started with Rails (3), Season 2RORLAB
 
Getting started with Rails (2), Season 2
Getting started with Rails (2), Season 2Getting started with Rails (2), Season 2
Getting started with Rails (2), Season 2RORLAB
 
Getting started with Rails (1), Season 2
Getting started with Rails (1), Season 2Getting started with Rails (1), Season 2
Getting started with Rails (1), Season 2RORLAB
 

More from RORLAB (20)

Getting Started with Rails (4)
Getting Started with Rails (4) Getting Started with Rails (4)
Getting Started with Rails (4)
 
Getting Started with Rails (3)
Getting Started with Rails (3) Getting Started with Rails (3)
Getting Started with Rails (3)
 
Getting Started with Rails (2)
Getting Started with Rails (2)Getting Started with Rails (2)
Getting Started with Rails (2)
 
Getting Started with Rails (1)
Getting Started with Rails (1)Getting Started with Rails (1)
Getting Started with Rails (1)
 
Self join in active record association
Self join in active record associationSelf join in active record association
Self join in active record association
 
Asset Pipeline in Ruby on Rails
Asset Pipeline in Ruby on RailsAsset Pipeline in Ruby on Rails
Asset Pipeline in Ruby on Rails
 
레일스가이드 한글번역 공개프로젝트 RORLabGuides 소개
레일스가이드 한글번역 공개프로젝트 RORLabGuides 소개레일스가이드 한글번역 공개프로젝트 RORLabGuides 소개
레일스가이드 한글번역 공개프로젝트 RORLabGuides 소개
 
Active Support Core Extension (3)
Active Support Core Extension (3)Active Support Core Extension (3)
Active Support Core Extension (3)
 
Active Support Core Extension (2)
Active Support Core Extension (2)Active Support Core Extension (2)
Active Support Core Extension (2)
 
Active Support Core Extensions (1)
Active Support Core Extensions (1)Active Support Core Extensions (1)
Active Support Core Extensions (1)
 
ActiveRecord Query Interface (2), Season 2
ActiveRecord Query Interface (2), Season 2ActiveRecord Query Interface (2), Season 2
ActiveRecord Query Interface (2), Season 2
 
Active Record Query Interface (1), Season 2
Active Record Query Interface (1), Season 2Active Record Query Interface (1), Season 2
Active Record Query Interface (1), Season 2
 
Active Record Association (2), Season 2
Active Record Association (2), Season 2Active Record Association (2), Season 2
Active Record Association (2), Season 2
 
ActiveRecord Association (1), Season 2
ActiveRecord Association (1), Season 2ActiveRecord Association (1), Season 2
ActiveRecord Association (1), Season 2
 
ActiveRecord Callbacks & Observers, Season 2
ActiveRecord Callbacks & Observers, Season 2ActiveRecord Callbacks & Observers, Season 2
ActiveRecord Callbacks & Observers, Season 2
 
ActiveRecord Validations, Season 2
ActiveRecord Validations, Season 2ActiveRecord Validations, Season 2
ActiveRecord Validations, Season 2
 
Rails Database Migration, Season 2
Rails Database Migration, Season 2Rails Database Migration, Season 2
Rails Database Migration, Season 2
 
Getting started with Rails (3), Season 2
Getting started with Rails (3), Season 2Getting started with Rails (3), Season 2
Getting started with Rails (3), Season 2
 
Getting started with Rails (2), Season 2
Getting started with Rails (2), Season 2Getting started with Rails (2), Season 2
Getting started with Rails (2), Season 2
 
Getting started with Rails (1), Season 2
Getting started with Rails (1), Season 2Getting started with Rails (1), Season 2
Getting started with Rails (1), Season 2
 

Action View Form Helpers - 1, Season 2

  • 1. Ror lab. season 2 - the 13th round - Action View Form Helpers - 1 December 29th, 2012 Hyoseong Choi
  • 2. form_tag • Two arguments 1. path for action : absolutely 1st argument 2. options hash • HTTP method : post(default), get, put, delete • HTML options : class, style, ...
  • 3. form_tag Basic Form <%= form_tag do %>   Form contents <% end %> app/views/home/index.html.erb current action <form accept-charset="UTF-8" action="/home/index" method="post">   <div style="margin:0;padding:0">     <input name="utf8" type="hidden" value="&#x2713;" />     <input name="authenticity_token" type="hidden" value="f755bb0ed134b76c432144748a6d4b7a7ddf2b71" />   </div>   Form contents to prevent </form> CSRF
  • 4. form_tag Multiple Hashes form_tag(:controller => "people", :action => "search", :method => "get", :class => "nifty_form") # => '<form accept-charset="UTF-8" action="/people/ search?method=get&class=nifty_form" method="post">' form_tag({:controller => "people", :action => "search"}, :method => "get", :class => "nifty_form") # => '<form accept-charset="UTF-8" action="/people/ search" method="get" class="nifty_form">'
  • 5. Helpers Generating Form Elements • text_field_tag • text_area_tag http://modernizr.com/docs/ • check_box_tag Modernizr • radio_button_tag yepnope • password_field_tag • hidden_field_tag polyfiller • search_field_tag • telephone_field_tag HTML5 controls • url_field_tag • email_field_tag http://en.wikipedia.org/wiki/Polyfill https://github.com/russfrisch/modernizr-rails
  • 7. HTML 5 “Form 2.0” Firefox v17.0.1 Safari v6.0.2 Chrome v23.0.1271.97 Opera v12.11
  • 8. HTML 5 “Form 2.0” Form Element Helpers Rails 3 HTML5 Input Types search_field search telephone_field tel url_field url email_field email number_field number range_field range Agile Web Development with Rails 4th edition
  • 9. HTML 5 “Form 2.0” Firefox v17.0.1 Safari v6.0.2 Chrome v23.0.1271.97 Opera v12.11
  • 10. Search Form for bookmark <%= 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">   <label for="q">Search for:</label>   <input id="q" name="q" type="text" />   <input name="commit" type="submit" value="Search" /> </form>
  • 11. Form Elements Helpers Checkboxes <%= check_box_tag(:pet_dog) %> <%= label_tag(:pet_dog, "I own a dog") %> <%= check_box_tag(:pet_cat) %> <%= label_tag(:pet_cat, "I own a cat") %> <input id="pet_dog" name="pet_dog" type="checkbox" value="1" /> <label for="pet_dog">I own a dog</label> <input id="pet_cat" name="pet_cat" type="checkbox" value="1" /> <label for="pet_cat">I own a cat</label>
  • 12. Form Elements Helpers Radio Buttons <%= radio_button_tag(:age, "child") %> <%= label_tag(:age_child, "I am younger than 21") %> <%= radio_button_tag(:age, "adult") %> <%= label_tag(:age_adult, "I'm over 21") %> <input id="age_child" name="age" type="radio" value="child" /> <label for="age_child">I am younger than 21</label> <input id="age_adult" name="age" type="radio" value="adult" /> <label for="age_adult">I'm over 21</label>
  • 13. Form Elements Helpers Others <input id="age_child" name="age" type="radio" value="child" /> <label for="age_child">I am younger than 21</label> <input id="age_adult" name="age" type="radio" value="adult" /> <label for="age_adult">I'm over 21</label> <input id="age_child" name="age" type="radio" value="child" /> <label for="age_child">I am younger than 21</label> <input id="age_adult" name="age" type="radio" value="adult" /> <label for="age_adult">I'm over 21</label>
  • 14. Model Object Helpers • check_box_tag • radio_button_tag • No _tag • text_area_tag • password_field_tag • hidden_field_tag
  • 15. for Model Object @person -> name : “Henry” <%= text_field(:person, :name) %> for an instance for a method variable name(attr.) <input id="person_name" name="person[name]" type="text" value="Henry"/>
  • 16. Binding a Form to an Object def new   @article = Article.new end <%= 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 %>
  • 17. <%= 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 %> <form accept-charset="UTF-8" action="/articles/ create" method="post" class="nifty_form">   <input id="article_title" name="article[title]" size="30" type="text" />   <textarea id="article_body" name="article[body]" cols="60" rows="12"></textarea>   <input name="commit" type="submit" value="Create" / > </form>
  • 19. fields_for Person •name •age •sex •address •telephone
  • 20. fields_for has_one or Person Contact has_many •name •address •age •telephone •sex belong_to using nested attributes
  • 21. fields_for class Person < ActiveRecord::Base has_one :contact, :dependent => :destroy end class Contact < ActiveRecord::Base belongs_to :person end using accepts_nested_attributes_for
  • 22. Using Resources resources :articles in config/routes.rb ## Creating a new article # long-style: form_for(@article, :url => articles_path) # short-style (record identification gets used): form_for(@article) ## Editing an existing article # long-style: form_for(@article, :url => article_path(@article), :html => { :method => "put" }) # short-style: form_for(@article)
  • 23. Using Namespaces namespace :admin do   resources :posts, :comments end in routes.rb form_for [:admin, @post] in _form.html.erb admin_post_path(@post) on update app/controllers/admin/posts_controller.rb app/controllers/admin/comments_controller.rb app/views/admin/posts/new.html.erb app/views/admin/posts/edit.html.erb
  • 24. HTTP Verbs • GET for all browsers • POST • PUT ? • DELETE
  • 25. PUT & DELETE • A hidden input : _method form_tag(search_path, :method => "put") <form accept-charset="UTF-8" action="/search" method="post">   <div style="margin:0;padding:0">     <input name="_method" type="hidden" value="put" />     <input name="utf8" type="hidden" value="&#x2713;" />     <input name="authenticity_token" type="hidden" value="f755bb0ed134b76c432144748a6d4b7a7ddf2b71" />   </div>   ...
  • 26. select_tag <select name="city_id" id="city_id">   <option value="1">Lisbon</option>   <option value="2">Madrid</option>   ...   <option value="12">Berlin</option> </select> <%= select_tag(:city_id, '<option value="1">Lisbon</ option>...') %>
  • 27. options_for_select <%= options_for_select([['Lisbon', 1], ['Madrid', 2], ...]) %>   1st argument => a nested array output:   <option value="1">Lisbon</option> <option value="2">Madrid</option> ... <%= select_tag(:city_id, options_for_select(...)) %>
  • 28. options_for_select <%= options_for_select([['Lisbon', 1], ['Madrid', 2], ...], 2) %>   output: 2nd argument => ‘selected’   <option value="1">Lisbon</option> <option value="2" selected="selected">Madrid</option>
  • 29. select for ORM # controller: @person = Person.new(:city_id => 2) # view: <%= select(:person, :city_id, [['Lisbon', 1], ['Madrid', 2], ...]) %> form builder pre-selected by Rails # select on a form builder <%= f.select(:city_id, ...) %>
  • 30. select from collection <% cities_array = City.all.map { |city| [city.name, city.id] } %> <%= options_for_select(cities_array) %> in short form, options_from_collection (City.all, :id, :name)
  • 31. collection_select collection_ <%= collection_select (:person, :city_id, City.all, :id, :name) %> or f. <%= f.collection_select (:city_id, City.all, :id, :name) %>
  • 33.   ROR Lab.