SlideShare une entreprise Scribd logo
1  sur  28
Télécharger pour lire hors ligne
Ror lab. season 2
   - the 14th round -



  Action View
Form Helpers -2
    January 12th, 2013

     Hyoseong Choi
Special Select
• time_zone_select
  : time_zone_options_for_select
• country_select
  : isolated to country_select plugin
• select_date : barebones helper
• date_select : model object helper
Time Zones
time_zone_select
                                                      model select
                                          attribute
                 <%= f.time_zone_select :time_zone,
priority_zones




                 [ ActiveSupport::TimeZone['Seoul'],
                 ActiveSupport::TimeZone['Tokyo'],ActiveSupport::TimeZ
                 one['Beijing'] ], :default => "Seoul" %>
time_zone_options_for_select
                                      bare-bones select

                      attribute
  <%= form_tag do %>                  selected
    <%= select_tag :time_zone,
          time_zone_options_for_select(nil,
              [




                                                     priority_zones
                ActiveSupport::TimeZone['Seoul'],
                ActiveSupport::TimeZone['Tokyo'],
                ActiveSupport::TimeZone['Beijing']
              ]
         ),
         :default => "Seoul" %>
  <% end %>
country_select
   • gem ‘country_select’
 <%= form_for(@person) do |f| %>
   <div class="field">
     <%= f.label :country %><br />
     <%= f.country_select :country,
             ["Korea, Republic of"] %>
   </div>
                           priority_countries
   <div class="actions">
     <%= f.submit %>
   </div>
 <% end %>




https://github.com/rails/country_select/blob/master/
lib/country_select.rb
select_date
<%= select_date Date.today, :prefix => :start_date %>




<select id="start_date_year"
        name="start_date[year]"> ... </select>
<select id="start_date_month"
        name="start_date[month]"> ... </select>
<select id="start_date_day"
        name="start_date[day]"> ... </select>




Date.civil(params[:start_date][:year].to_i,
params[:start_date][:month].to_i, params[:start_date]
[:day].to_i)
Individual Selects
• select_year
• select_month
• select_day      :prefix defaults to “date”
• select_hour
• select_minute
• select_second
cf. select_date
date_select
<%= date_select :person, :birth_date %>




<select id="person_birth_date_1i"
        name="person[birth_date(1i)]"> ... </select>
<select id="person_birth_date_2i"
        name="person[birth_date(2i)]"> ... </select>
<select id="person_birth_date_3i"
        name="person[birth_date(3i)]"> ... </select>




{:person => {'birth_date(1i)' => '2008',
'birth_date(2i)' => '11', 'birth_date(3i)' => '22'}}
Uploading Files
params[:picture]
 <%= form_tag({:action => :upload}, :multipart =>
 true) do %>
   <%= file_field_tag 'picture' %>
 <% end %>
  
 <%= form_for @person, :multipart => true do |f| %>
   <%= f.file_field :picture %>
 <% end %>

params[:person][:picture]
Since Rails 3.1, it automatically sets the multipart/
form-data with file_field in the form_for
What gets
           uploaded
def upload
  uploaded_io = params[:person][:picture]
  uploaded_io
  File.open(Rails.root.join('public', 'uploads',
uploaded_io.original_filename), 'w') do |file|
    file.write(uploaded_io.read)
  end                             wb
end




an instance of a subclass of IO
   • original_filename
   • content_type : MIME type
UploadedFile
               CLASS ActionDispatch::Http::UploadedFile




"uploaded_file"=>
#<ActionDispatch::Http::UploadedFile:0x007fd288c8fed0
  @original_filename="korean_flag.png",
  @content_type="image/png",
  @headers="Content-Disposition: form-data; name="person[uploaded]";
filename="korean_flag.png"rnContent-Type: image/pngrn",
  @tempfile=
    #<File:/var/folders/rv/q26ztr693k5_58wbggd_jl300000gn/T/
RackMultipart20130107-90570-18x3nfy>
>
Upload Gems
• System Requirement : ImageMagick
• CarrierWave,
 • more flexiable than Paperclip
 • Rmagick gem, required!
• Paperclip
Ajaxing Upload

• “remotipart” gem
  : AJAX style file uploads with jQuery

  https://github.com/leppert/remotipart
Customizing Form
            Builders                                                                   Pro



  using
 helper       <%= form_for @person do |f| %>
 method         <%= text_field_with_label f, :first_name %>
              <% end %>

    or
                <%= form_for @person, :builder => LabellingFormBuilder do |
                f| %>
   using
                  <%= f.text_field :first_name %>
subclassing     <% end %>



                class LabellingFormBuilder <
                ActionView::Helpers::FormBuilder
                  def text_field(attribute, options={})
                    label(attribute) + super
                  end
                end
                                         app/form_builders/labelling_form_builder.rb
Simple_form



•   https://github.com/plataformatec/simple_form
•   with Twitter Boostrap
•   with Foundation 3
Params Naming
  Client           Server

    Form
for model obj
                params[:person]
 “@person”

   submit
Basic Structures
               Arrays & Hashes

<input id="person_name" name="person[name]"

      type="text" value="Henry"/>


params hash
      {‘person’ => {‘name’ => ‘Henry’}}

params[:person]
       {‘name’ => ‘Henry’}

params[:person][:name]
       ‘Henry’
Nested Hashes
<input id="person_address_city"
      name="person[address][city]"
      type="text" value="New York"/>



params hash
      {'person' => {'address' => {'city' => 'New York'}}}
Duplicated Params
                                 array


 <input name="person[phone_number][]" type="text"/>
 <input name="person[phone_number][]" type="text"/>
 <input name="person[phone_number][]" type="text"/>




params[:person][:phone_number]
array        [
                    ’02-333-1234’,
                    ‘031-323-9898’,
                    ‘062-546-2323’
                ]
hash & array


   Mixed Params
   hash nth-nested but array only one-level

<input name="addresses[][line1]" type="text"/>
<input name="addresses[][line2]" type="text"/>
<input name="addresses[][city]" type="text"/>




params[:addresses]             array

                                       hash
      [
          {
              ‘line1’ => ’02-333-1234’,
              ‘line2’ => ‘031-323-9898’,
              ‘city’ => ‘seoul’
          }
      ]
Using Form
             Helpers
<%= form_for @person do |person_form| %>
  <%= person_form.text_field :name %>             address.id
  <% @person.addresses.each do |address| %>
    <%= person_form.fields_for address, :index => address do
|address_form|%>
      <%= address_form.text_field :city %>
    <% end %>
  <% end %>
<% end %>



<form accept-charset="UTF-8" action="/people/1" class="edit_person"
id="edit_person_1" method="post">
  <input id="person_name" name="person[name]" size="30" type="text" />
  <input id="person_address_23_city" name="person[address][23][city]" size="30"
type="text" />
  <input id="person_address_45_city" name="person[address][45][city]" size="30"
type="text" />
</form>
Using Form
         Helpers
params

{
    'person' =>
    {
       'name' =>   'Bob',
       'address'   =>
       {
         '23' =>   {'city' => 'Paris'},
         '45' =>   {'city' => 'London'}
       }
    }
}
Using :index
     <%= fields_for 'person[address][primary]',
     address, :index => address do |address_form| %>
       <%= address_form.text_field :city %>
     <% end %>
or
     <%= fields_for 'person[address][primary][]', address
     do |address_form| %>
       <%= address_form.text_field :city %>
     <% end %>



     <input id="person_address_primary_1_city"
     name="person[address][primary][1][city]" type="text"
     value="bologna" />
Form to External
  Resources - 1
form_tag

 <%= form_tag 'http://farfar.away/
 form', :authenticity_token => 'external_token') do %>
   Form contents
 <% end %>



 <%= form_tag 'http://farfar.away/
                               false
 form', :authenticity_token => false) do %>
   Form contents
 <% end %>                 payment gateway
Form to External
  Resources - 2
form_for

 <%= form_for @invoice, :url =>
 external_url, :authenticity_token => 'external_token'
 do |f|
   Form contents
 <% end %>



 <%= form_for @invoice, :url =>
 external_url, :authenticity_token => false do |f|
   Form contents
 <% end %>
Complex forms
ROR Lab. screencasts
Railscasts by Ryan Bates
•   Complex Forms Part 1 - Episode #73

•   Complex Forms Part II - Episode #74

•   Complex Forms Part III - Episode #75

•   Nested Model Form (revised) - Episode #196
감사합니다.

Contenu connexe

Tendances

Юрий Буянов «Squeryl — ORM с человеческим лицом»
Юрий Буянов «Squeryl — ORM с человеческим лицом»Юрий Буянов «Squeryl — ORM с человеческим лицом»
Юрий Буянов «Squeryl — ORM с человеческим лицом»e-Legion
 
Custom Signals for Uncoupled Design
Custom Signals for Uncoupled DesignCustom Signals for Uncoupled Design
Custom Signals for Uncoupled Designecomsmith
 
Everything you always wanted to know about forms* *but were afraid to ask
Everything you always wanted to know about forms* *but were afraid to askEverything you always wanted to know about forms* *but were afraid to ask
Everything you always wanted to know about forms* *but were afraid to askAndrea Giuliano
 
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.8pedroburonv
 
Data Binding: Is It the Next Big Thing?
Data Binding: Is It the Next Big Thing?Data Binding: Is It the Next Big Thing?
Data Binding: Is It the Next Big Thing?GlobalLogic Ukraine
 
HTML5 and CSS3 Refresher
HTML5 and CSS3 RefresherHTML5 and CSS3 Refresher
HTML5 and CSS3 RefresherIvano Malavolta
 
Laravel 로 배우는 서버사이드 #5
Laravel 로 배우는 서버사이드 #5Laravel 로 배우는 서버사이드 #5
Laravel 로 배우는 서버사이드 #5성일 한
 
Mashing up JavaScript – Advanced Techniques for modern Web Apps
Mashing up JavaScript – Advanced Techniques for modern Web AppsMashing up JavaScript – Advanced Techniques for modern Web Apps
Mashing up JavaScript – Advanced Techniques for modern Web AppsBastian Hofmann
 
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
 
Internet programming lab manual
Internet programming lab manualInternet programming lab manual
Internet programming lab manualinteldualcore
 
Intro programacion funcional
Intro programacion funcionalIntro programacion funcional
Intro programacion funcionalNSCoder Mexico
 

Tendances (18)

Юрий Буянов «Squeryl — ORM с человеческим лицом»
Юрий Буянов «Squeryl — ORM с человеческим лицом»Юрий Буянов «Squeryl — ORM с человеческим лицом»
Юрий Буянов «Squeryl — ORM с человеческим лицом»
 
Custom Signals for Uncoupled Design
Custom Signals for Uncoupled DesignCustom Signals for Uncoupled Design
Custom Signals for Uncoupled Design
 
Borrador del blog
Borrador del blogBorrador del blog
Borrador del blog
 
Jquery 3
Jquery 3Jquery 3
Jquery 3
 
Everything you always wanted to know about forms* *but were afraid to ask
Everything you always wanted to know about forms* *but were afraid to askEverything you always wanted to know about forms* *but were afraid to ask
Everything you always wanted to know about forms* *but were afraid to ask
 
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
 
Data Binding: Is It the Next Big Thing?
Data Binding: Is It the Next Big Thing?Data Binding: Is It the Next Big Thing?
Data Binding: Is It the Next Big Thing?
 
Leveraging Symfony2 Forms
Leveraging Symfony2 FormsLeveraging Symfony2 Forms
Leveraging Symfony2 Forms
 
Mashing up JavaScript
Mashing up JavaScriptMashing up JavaScript
Mashing up JavaScript
 
Django quickstart
Django quickstartDjango quickstart
Django quickstart
 
HTML5 and CSS3 Refresher
HTML5 and CSS3 RefresherHTML5 and CSS3 Refresher
HTML5 and CSS3 Refresher
 
Laravel 로 배우는 서버사이드 #5
Laravel 로 배우는 서버사이드 #5Laravel 로 배우는 서버사이드 #5
Laravel 로 배우는 서버사이드 #5
 
The Settings API
The Settings APIThe Settings API
The Settings API
 
Mashing up JavaScript – Advanced Techniques for modern Web Apps
Mashing up JavaScript – Advanced Techniques for modern Web AppsMashing up JavaScript – Advanced Techniques for modern Web Apps
Mashing up JavaScript – Advanced Techniques for modern Web Apps
 
Advanced Django
Advanced DjangoAdvanced Django
Advanced Django
 
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
 
Internet programming lab manual
Internet programming lab manualInternet programming lab manual
Internet programming lab manual
 
Intro programacion funcional
Intro programacion funcionalIntro programacion funcional
Intro programacion funcional
 

En vedette

레일스가이드 한글번역 공개프로젝트 RORLabGuides 소개
레일스가이드 한글번역 공개프로젝트 RORLabGuides 소개레일스가이드 한글번역 공개프로젝트 RORLabGuides 소개
레일스가이드 한글번역 공개프로젝트 RORLabGuides 소개RORLAB
 
Getting Started with Rails (1)
Getting Started with Rails (1)Getting Started with Rails (1)
Getting Started with Rails (1)RORLAB
 
Active Support Core Extension (2)
Active Support Core Extension (2)Active Support Core Extension (2)
Active Support Core Extension (2)RORLAB
 
Rails Database Migration, Season 2
Rails Database Migration, Season 2Rails Database Migration, Season 2
Rails Database Migration, 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
 
Securing Rails
Securing RailsSecuring Rails
Securing RailsAlex Payne
 
ActiveRecord Validations, Season 2
ActiveRecord Validations, Season 2ActiveRecord Validations, Season 2
ActiveRecord Validations, Season 2RORLAB
 

En vedette (7)

레일스가이드 한글번역 공개프로젝트 RORLabGuides 소개
레일스가이드 한글번역 공개프로젝트 RORLabGuides 소개레일스가이드 한글번역 공개프로젝트 RORLabGuides 소개
레일스가이드 한글번역 공개프로젝트 RORLabGuides 소개
 
Getting Started with Rails (1)
Getting Started with Rails (1)Getting Started with Rails (1)
Getting Started with Rails (1)
 
Active Support Core Extension (2)
Active Support Core Extension (2)Active Support Core Extension (2)
Active Support Core Extension (2)
 
Rails Database Migration, Season 2
Rails Database Migration, Season 2Rails Database Migration, Season 2
Rails Database Migration, 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
 
Securing Rails
Securing RailsSecuring Rails
Securing Rails
 
ActiveRecord Validations, Season 2
ActiveRecord Validations, Season 2ActiveRecord Validations, Season 2
ActiveRecord Validations, Season 2
 

Similaire à Action View Form Helpers - 2, Season 2

Building Web Service Clients with ActiveModel
Building Web Service Clients with ActiveModelBuilding Web Service Clients with ActiveModel
Building Web Service Clients with ActiveModelpauldix
 
Building Web Service Clients with ActiveModel
Building Web Service Clients with ActiveModelBuilding Web Service Clients with ActiveModel
Building Web Service Clients with ActiveModelpauldix
 
Acceptance Testing with Webrat
Acceptance Testing with WebratAcceptance Testing with Webrat
Acceptance Testing with WebratLuismi Cavallé
 
Engines: Team Development on Rails (2005)
Engines: Team Development on Rails (2005)Engines: Team Development on Rails (2005)
Engines: Team Development on Rails (2005)lazyatom
 
Rails 3 overview
Rails 3 overviewRails 3 overview
Rails 3 overviewYehuda Katz
 
Boston Computing Review - Ruby on Rails
Boston Computing Review - Ruby on RailsBoston Computing Review - Ruby on Rails
Boston Computing Review - Ruby on RailsJohn Brunswick
 
Understanding form helpers
Understanding form helpersUnderstanding form helpers
Understanding form helpersBruno Almeida
 
Rugalytics | Ruby Manor Nov 2008
Rugalytics | Ruby Manor Nov 2008Rugalytics | Ruby Manor Nov 2008
Rugalytics | Ruby Manor Nov 2008Rob
 
Django Forms: Best Practices, Tips, Tricks
Django Forms: Best Practices, Tips, TricksDjango Forms: Best Practices, Tips, Tricks
Django Forms: Best Practices, Tips, TricksShawn Rider
 
Implementation of GUI Framework part3
Implementation of GUI Framework part3Implementation of GUI Framework part3
Implementation of GUI Framework part3masahiroookubo
 
Your Custom WordPress Admin Pages Suck
Your Custom WordPress Admin Pages SuckYour Custom WordPress Admin Pages Suck
Your Custom WordPress Admin Pages SuckAnthony Montalbano
 
Angular 2 Component Communication - Talk by Rob McDiarmid
Angular 2 Component Communication - Talk by Rob McDiarmidAngular 2 Component Communication - Talk by Rob McDiarmid
Angular 2 Component Communication - Talk by Rob McDiarmidAmrita Chopra
 
More to RoC weibo
More to RoC weiboMore to RoC weibo
More to RoC weiboshaokun
 
How to disassemble one monster app into an ecosystem of 30
How to disassemble one monster app into an ecosystem of 30How to disassemble one monster app into an ecosystem of 30
How to disassemble one monster app into an ecosystem of 30fiyuer
 
Ruby on rails
Ruby on rails Ruby on rails
Ruby on rails Mohit Jain
 
GHC Participant Training
GHC Participant TrainingGHC Participant Training
GHC Participant TrainingAidIQ
 
Form using html and java script validation
Form using html and java script validationForm using html and java script validation
Form using html and java script validationMaitree Patel
 

Similaire à Action View Form Helpers - 2, Season 2 (20)

Building Web Service Clients with ActiveModel
Building Web Service Clients with ActiveModelBuilding Web Service Clients with ActiveModel
Building Web Service Clients with ActiveModel
 
Building Web Service Clients with ActiveModel
Building Web Service Clients with ActiveModelBuilding Web Service Clients with ActiveModel
Building Web Service Clients with ActiveModel
 
Acceptance Testing with Webrat
Acceptance Testing with WebratAcceptance Testing with Webrat
Acceptance Testing with Webrat
 
Engines: Team Development on Rails (2005)
Engines: Team Development on Rails (2005)Engines: Team Development on Rails (2005)
Engines: Team Development on Rails (2005)
 
Rails 3 overview
Rails 3 overviewRails 3 overview
Rails 3 overview
 
Rails <form> Chronicle
Rails <form> ChronicleRails <form> Chronicle
Rails <form> Chronicle
 
Boston Computing Review - Ruby on Rails
Boston Computing Review - Ruby on RailsBoston Computing Review - Ruby on Rails
Boston Computing Review - Ruby on Rails
 
Understanding form helpers
Understanding form helpersUnderstanding form helpers
Understanding form helpers
 
Rugalytics | Ruby Manor Nov 2008
Rugalytics | Ruby Manor Nov 2008Rugalytics | Ruby Manor Nov 2008
Rugalytics | Ruby Manor Nov 2008
 
JSP
JSPJSP
JSP
 
Django Forms: Best Practices, Tips, Tricks
Django Forms: Best Practices, Tips, TricksDjango Forms: Best Practices, Tips, Tricks
Django Forms: Best Practices, Tips, Tricks
 
Implementation of GUI Framework part3
Implementation of GUI Framework part3Implementation of GUI Framework part3
Implementation of GUI Framework part3
 
Your Custom WordPress Admin Pages Suck
Your Custom WordPress Admin Pages SuckYour Custom WordPress Admin Pages Suck
Your Custom WordPress Admin Pages Suck
 
Angular 2 Component Communication - Talk by Rob McDiarmid
Angular 2 Component Communication - Talk by Rob McDiarmidAngular 2 Component Communication - Talk by Rob McDiarmid
Angular 2 Component Communication - Talk by Rob McDiarmid
 
More to RoC weibo
More to RoC weiboMore to RoC weibo
More to RoC weibo
 
Webtechnology lab
Webtechnology labWebtechnology lab
Webtechnology lab
 
How to disassemble one monster app into an ecosystem of 30
How to disassemble one monster app into an ecosystem of 30How to disassemble one monster app into an ecosystem of 30
How to disassemble one monster app into an ecosystem of 30
 
Ruby on rails
Ruby on rails Ruby on rails
Ruby on rails
 
GHC Participant Training
GHC Participant TrainingGHC Participant Training
GHC Participant Training
 
Form using html and java script validation
Form using html and java script validationForm using html and java script validation
Form using html and java script validation
 

Plus de 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
 
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
 
Active Support Core Extension (3)
Active Support Core Extension (3)Active Support Core Extension (3)
Active Support Core Extension (3)RORLAB
 
Active Support Core Extensions (1)
Active Support Core Extensions (1)Active Support Core Extensions (1)
Active Support Core Extensions (1)RORLAB
 
Action Controller Overview, Season 2
Action Controller Overview, Season 2Action Controller Overview, Season 2
Action Controller Overview, Season 2RORLAB
 
Layouts and Rendering in Rails, Season 2
Layouts and Rendering in Rails, Season 2Layouts and Rendering in Rails, Season 2
Layouts and Rendering in Rails, Season 2RORLAB
 
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
 
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
 
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
 
Routing 2, Season 1
Routing 2, Season 1Routing 2, Season 1
Routing 2, Season 1RORLAB
 
Routing 1, Season 1
Routing 1, Season 1Routing 1, Season 1
Routing 1, Season 1RORLAB
 
Action Controller Overview, Season 1
Action Controller Overview, Season 1Action Controller Overview, Season 1
Action Controller Overview, Season 1RORLAB
 
Active Record Form Helpers, Season 1
Active Record Form Helpers, Season 1Active Record Form Helpers, Season 1
Active Record Form Helpers, Season 1RORLAB
 

Plus de 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)
 
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
 
Active Support Core Extension (3)
Active Support Core Extension (3)Active Support Core Extension (3)
Active Support Core Extension (3)
 
Active Support Core Extensions (1)
Active Support Core Extensions (1)Active Support Core Extensions (1)
Active Support Core Extensions (1)
 
Action Controller Overview, Season 2
Action Controller Overview, Season 2Action Controller Overview, Season 2
Action Controller Overview, Season 2
 
Layouts and Rendering in Rails, Season 2
Layouts and Rendering in Rails, Season 2Layouts and Rendering in Rails, Season 2
Layouts and Rendering in Rails, Season 2
 
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
 
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
 
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
 
Routing 2, Season 1
Routing 2, Season 1Routing 2, Season 1
Routing 2, Season 1
 
Routing 1, Season 1
Routing 1, Season 1Routing 1, Season 1
Routing 1, Season 1
 
Action Controller Overview, Season 1
Action Controller Overview, Season 1Action Controller Overview, Season 1
Action Controller Overview, Season 1
 
Active Record Form Helpers, Season 1
Active Record Form Helpers, Season 1Active Record Form Helpers, Season 1
Active Record Form Helpers, Season 1
 

Dernier

1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxVishalSingh1417
 
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-IIFood Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-IIShubhangi Sonawane
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docxPoojaSen20
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701bronxfugly43
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...Poonam Aher Patil
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docxPoojaSen20
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 

Dernier (20)

1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-IIFood Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 

Action View Form Helpers - 2, Season 2

  • 1. Ror lab. season 2 - the 14th round - Action View Form Helpers -2 January 12th, 2013 Hyoseong Choi
  • 2. Special Select • time_zone_select : time_zone_options_for_select • country_select : isolated to country_select plugin • select_date : barebones helper • date_select : model object helper
  • 4. time_zone_select model select attribute <%= f.time_zone_select :time_zone, priority_zones [ ActiveSupport::TimeZone['Seoul'], ActiveSupport::TimeZone['Tokyo'],ActiveSupport::TimeZ one['Beijing'] ], :default => "Seoul" %>
  • 5. time_zone_options_for_select bare-bones select attribute <%= form_tag do %> selected <%= select_tag :time_zone, time_zone_options_for_select(nil, [ priority_zones ActiveSupport::TimeZone['Seoul'], ActiveSupport::TimeZone['Tokyo'], ActiveSupport::TimeZone['Beijing'] ] ), :default => "Seoul" %> <% end %>
  • 6. country_select • gem ‘country_select’ <%= form_for(@person) do |f| %> <div class="field"> <%= f.label :country %><br /> <%= f.country_select :country, ["Korea, Republic of"] %> </div> priority_countries <div class="actions"> <%= f.submit %> </div> <% end %> https://github.com/rails/country_select/blob/master/ lib/country_select.rb
  • 7. select_date <%= select_date Date.today, :prefix => :start_date %> <select id="start_date_year" name="start_date[year]"> ... </select> <select id="start_date_month" name="start_date[month]"> ... </select> <select id="start_date_day" name="start_date[day]"> ... </select> Date.civil(params[:start_date][:year].to_i, params[:start_date][:month].to_i, params[:start_date] [:day].to_i)
  • 8. Individual Selects • select_year • select_month • select_day :prefix defaults to “date” • select_hour • select_minute • select_second cf. select_date
  • 9. date_select <%= date_select :person, :birth_date %> <select id="person_birth_date_1i" name="person[birth_date(1i)]"> ... </select> <select id="person_birth_date_2i" name="person[birth_date(2i)]"> ... </select> <select id="person_birth_date_3i" name="person[birth_date(3i)]"> ... </select> {:person => {'birth_date(1i)' => '2008', 'birth_date(2i)' => '11', 'birth_date(3i)' => '22'}}
  • 10. Uploading Files params[:picture] <%= form_tag({:action => :upload}, :multipart => true) do %>   <%= file_field_tag 'picture' %> <% end %>   <%= form_for @person, :multipart => true do |f| %>   <%= f.file_field :picture %> <% end %> params[:person][:picture] Since Rails 3.1, it automatically sets the multipart/ form-data with file_field in the form_for
  • 11. What gets uploaded def upload   uploaded_io = params[:person][:picture] uploaded_io   File.open(Rails.root.join('public', 'uploads', uploaded_io.original_filename), 'w') do |file|     file.write(uploaded_io.read)   end wb end an instance of a subclass of IO • original_filename • content_type : MIME type
  • 12. UploadedFile CLASS ActionDispatch::Http::UploadedFile "uploaded_file"=> #<ActionDispatch::Http::UploadedFile:0x007fd288c8fed0 @original_filename="korean_flag.png", @content_type="image/png", @headers="Content-Disposition: form-data; name="person[uploaded]"; filename="korean_flag.png"rnContent-Type: image/pngrn", @tempfile= #<File:/var/folders/rv/q26ztr693k5_58wbggd_jl300000gn/T/ RackMultipart20130107-90570-18x3nfy> >
  • 13. Upload Gems • System Requirement : ImageMagick • CarrierWave, • more flexiable than Paperclip • Rmagick gem, required! • Paperclip
  • 14. Ajaxing Upload • “remotipart” gem : AJAX style file uploads with jQuery https://github.com/leppert/remotipart
  • 15. Customizing Form Builders Pro using helper <%= form_for @person do |f| %> method   <%= text_field_with_label f, :first_name %> <% end %> or <%= form_for @person, :builder => LabellingFormBuilder do | f| %> using   <%= f.text_field :first_name %> subclassing <% end %> class LabellingFormBuilder < ActionView::Helpers::FormBuilder   def text_field(attribute, options={})     label(attribute) + super   end end app/form_builders/labelling_form_builder.rb
  • 16. Simple_form • https://github.com/plataformatec/simple_form • with Twitter Boostrap • with Foundation 3
  • 17. Params Naming Client Server Form for model obj params[:person] “@person” submit
  • 18. Basic Structures Arrays & Hashes <input id="person_name" name="person[name]" type="text" value="Henry"/> params hash {‘person’ => {‘name’ => ‘Henry’}} params[:person] {‘name’ => ‘Henry’} params[:person][:name] ‘Henry’
  • 19. Nested Hashes <input id="person_address_city" name="person[address][city]" type="text" value="New York"/> params hash {'person' => {'address' => {'city' => 'New York'}}}
  • 20. Duplicated Params array <input name="person[phone_number][]" type="text"/> <input name="person[phone_number][]" type="text"/> <input name="person[phone_number][]" type="text"/> params[:person][:phone_number] array [ ’02-333-1234’, ‘031-323-9898’, ‘062-546-2323’ ]
  • 21. hash & array Mixed Params hash nth-nested but array only one-level <input name="addresses[][line1]" type="text"/> <input name="addresses[][line2]" type="text"/> <input name="addresses[][city]" type="text"/> params[:addresses] array hash [ { ‘line1’ => ’02-333-1234’, ‘line2’ => ‘031-323-9898’, ‘city’ => ‘seoul’ } ]
  • 22. Using Form Helpers <%= form_for @person do |person_form| %>   <%= person_form.text_field :name %> address.id   <% @person.addresses.each do |address| %>     <%= person_form.fields_for address, :index => address do |address_form|%>       <%= address_form.text_field :city %>     <% end %>   <% end %> <% end %> <form accept-charset="UTF-8" action="/people/1" class="edit_person" id="edit_person_1" method="post">   <input id="person_name" name="person[name]" size="30" type="text" />   <input id="person_address_23_city" name="person[address][23][city]" size="30" type="text" />   <input id="person_address_45_city" name="person[address][45][city]" size="30" type="text" /> </form>
  • 23. Using Form Helpers params { 'person' => { 'name' => 'Bob', 'address' => { '23' => {'city' => 'Paris'}, '45' => {'city' => 'London'} } } }
  • 24. Using :index <%= fields_for 'person[address][primary]', address, :index => address do |address_form| %>   <%= address_form.text_field :city %> <% end %> or <%= fields_for 'person[address][primary][]', address do |address_form| %>   <%= address_form.text_field :city %> <% end %> <input id="person_address_primary_1_city" name="person[address][primary][1][city]" type="text" value="bologna" />
  • 25. Form to External Resources - 1 form_tag <%= form_tag 'http://farfar.away/ form', :authenticity_token => 'external_token') do %>   Form contents <% end %> <%= form_tag 'http://farfar.away/ false form', :authenticity_token => false) do %>   Form contents <% end %> payment gateway
  • 26. Form to External Resources - 2 form_for <%= form_for @invoice, :url => external_url, :authenticity_token => 'external_token' do |f|   Form contents <% end %> <%= form_for @invoice, :url => external_url, :authenticity_token => false do |f|   Form contents <% end %>
  • 27. Complex forms ROR Lab. screencasts Railscasts by Ryan Bates • Complex Forms Part 1 - Episode #73 • Complex Forms Part II - Episode #74 • Complex Forms Part III - Episode #75 • Nested Model Form (revised) - Episode #196
  • 29.   ROR Lab.