SlideShare a Scribd company logo
1 of 88
Download to read offline
Rails <form> Chronicle
history of “name” attribute and form_* helper methods.



                    2008 / 2 / 16
      PostgreSQL                / Ruby


                             / Rails     @
•( )
  • Ruby   Rails

• Rails      @

•
Acknowledgments
•
•            PostgreSQL   /

 Ruby

•
•
•Rails   @

•
Acknowledgments
•     (       )   Rails

    • Rails
    • Ruby
Contact me

•k-morohashi@esm.co.jp (work)
•moronatural@gmail.com (private)
•http://d.hatena.ne.jp/moro/
 •                                 :- )
•
       blog FeedList

http://feedlist.net/
Conclusion
  •                   /


# in app/controllers/entries_controller.rb
entry = Entry.new(params[:entry])


   •
   •form
What is <form>?
<form> is an          HTML element.
• form
•                      HTTP


 <form id=”new_entry” action=”/entries” method=”POST”>
    <label for=”entry_title”>Title</label>
    <input type=”text” id=”entry_title” name=”entry[title]” />

    <label for=”entry_body”>Body</label>
    <textarea id=”entry_body” name=”entry[body]”></textarea>
 </form>
<form> is an   Interface.
•
    User Interface.
<form> has some           Controls.
  •               Control       (input or so)

  • Control        name

<form id=”new_entry” action=”/entries” method=”POST”>
    <label for=”entry_title”>Title</label>
    <input type=”text” id=”entry_title”
           name=”entry[title]”       />

    <label for=”entry_body”>Body</label>
    <textarea id=”entry_body”   name=”entry[body]”>
    </textarea>
</form>
What is control’s

        “name” attribute.
• name

    •

•
    “name”
“name” attribute is
    the Programming Interface

• form   API !

 •                 name    API !

•         action      method
<form> is an   Interface.

•
      User Interface

•
               Programing Interface
How does Rails
  handle?
Phase 1



From View to
  Controller
Rails handle query parameters

            like a Hash
•Rails                    Hash


POST /entry
  entry[title]=new title&entry[body]=new body




params()
# =>{ :entry => {:title => “new title”,
                 :body => ”new body”}}
Examples
<form action=”...”>
  <input name=”title” type=”text” />
  <input name=”body” type=”text” />
</form>




{:title => “new title”, :body   => ”new body”}
Examples
<form action=”...”>
  <input name=”entry[title]” type=”text” />
  <input name=”entry[body]” type=”text” />
</form>




{ :entry => {:title => “new title”,
             :body => ”new body” }}
Examples
<form action=quot;...quot;>
  <input type=quot;textquot;   name=quot;entry[title]quot; />
  <input type=quot;textquot;   name=quot;entry[links][]quot; />
  <input type=quot;textquot;   name=quot;entry[links][]quot; />
  <input type=quot;textquot;   name=quot;entry[links][]quot; />
</form>




{quot;entryquot;=>{quot;titlequot;=>quot;aaaquot;,
           quot;linksquot;=>[quot;xxxquot;, quot;yyyquot;, quot;zzzquot;]}}
Phase 2



From Controller to
  Model (and DB)
Rails handle Hash as
AR constructor argument.
• Rails   Hash ActiveRecord




hash = { :entry => {:title => “new title”,
                    :body => ”new body”}}

entry = Entry.new(hash[:entry])
entry.title # => “new title”
And, of course, Rails can
    save AR object to DB
•             Rails   ActiveRecord       DB




entry = Entry.new(hash)
entry.title # => “new title”

entry.save
Therefore Rails can
save form-data to DB at ease.
•        Rails        form
                 DB


entry = Entry.new(params[:entry])

entry.save
In other words,

entry = Entry.new(params[:entry])


 • params[      ]



 •       form            name
Rails <form> Chronicle

 history of “name” attribute and
     form_* helper methods.
~ Rails 1.0
Before form_for()
form_tag(url_for_options = {},
         options = {},
         *parameters_for_url)


• Rails 1.0          <form>



• HTML        form

 •   action            url_for_options

 •                        options
Thin wrapper for
        HTML <form> tag.
form_tag(
  {:controller=>”entries”,:action=>”create”},
  {:id=>”new_entry”, :method=>”post”} )


                  generates


<form id=”new_entry” method=”POST”
      action=>”entries/create”>
and
there is lovely end_form_tag()

    # Outputs “</form>”
    def end_form_tag
      “</form>”
    end
ActionView::Helpers::
                 FormHelper.
•                           FormHelper            !!

    @entry = Entry.new(:title=>”      ”)
    text_field(:entry, :title)

    # => <input type=”text”
                name=”entry[title]”
                value=”       ” />


• ActiveRecord               (=DB     )    form
ActionView::Helpers::
             FormHelper.
@entry = Entry.new(:title=>”             ”)
text_field(:entry, :title)

# => <input type=”text”
            name=”entry[title]”
            value=”       ” />

               and you will get

{:entry => {:title => “           ” }}
ActionView::Helpers::
                FormHelper.
    text_field(object, method, options={})


•                                object
                 ”@#{object}”

•        method

• “#{object}[#{name}]”           name     input
rem
          ind
                Examples
<form action=”...”>
  <input name=”entry[title]” type=”text” />
  <input name=”entry[body]” type=”text” />
</form>




{ :entry => {:title => “new title”,
             :body => ”new body” }}
Rails 1.1& Rails1.2
  form_for() has come.
form_for( object_name,
          *args, &proc)


• Rails 1.1
 •
 •   URL

 •
• “Creates a form and a scope around a specific
  model object, ”(from API Document)
form for the object.

•
    •   text_field()

    •                 ==


<%# @entry                 %>
<% form_for(:entry,
            :url=>{:action=>”crate”}) do |f| %>
  ...
<% end %>
form_for()
            remembers the object.
•
                       ActionView::FormBuilder

• text_field(method, options={})
    •   cf : text_field(object, method, options={}) in Rails 1.0

<% form_for(:entry,
            :url=>{:action=>”crate”}) do |f| %>
    # @entry#title        text field

  <label>Title</label>
  <%= f.text_field :title %>
<% end %>
ActionView::
               FormBuilder
<% form_for(:entry,
            :url=>{:action=>”crate”}) do |f| %>
  <label>Title</label>
  <%= f.text_field :title %>
<% end %>

                      generates

<form action=quot;/entries/createquot; method=quot;postquot;>
  <label>Title</label>
  <input id=quot;entry_titlequot; name=quot;entry[title]quot;
         size=quot;30quot; type=quot;textquot; />
</form>
FYI: 2nd argument.
•
<% entry_local = Entry.new(:title=>”local”) %>

<% form_for(:entry,
            entry_local,
            :url=>{:action=>”crate”}) do |f| %>
  <label>Title</label>
  <%= f.text_field :title %>
<% end %>


• respond_to?(:title)                             OK
OK, but

                 Why form_for()?
rem i
      nd
          • Rails                 Hash

re min
       d
          • “Creates a form and a scope around a
              specific model object, ”

          •                  CRUD        HTML


           •                     ↑↑
OK, but

    Does it works well?

•               has_many :through

•            CRUD



•    RDBMS
But...
• form_for
    (Rails          @          )

 •
 •   end_form_tag() obsolete


•             (?)

•
Rails 2.0

form_for() meets Resource
form_for() and map.resource


• AR                  ”resource”

•“resource”   HTTP   CRUD



  ActionController::Routes.draw do |m|
    map.resources :entries
  end
new form_for()
<% @entry = Entry.find(1) %>

<% form_for(@entry) do |f|%>
  ...
<% end %>

                      generates
<form action=quot;/entries/1quot; class=quot;edit_entryquot;
  id=quot;edit_entry_1quot; method=quot;postquot;>

  <input name=quot;_methodquot; type=quot;hiddenquot; value=quot;putquot; />
  ...
</form>
form_for()
     determine the form identity.
<form action=quot;/entries/1quot;   class=quot;edit_entryquot;
     id=quot;edit_entry_1quot;      method=quot;postquot;>

  <input name=quot;_methodquot; type=quot;hiddenquot; value=quot;putquot; />
  ...
</form>


• ActiveRecord
 Convention
 •          class   ID
new Convention for
             DOM ID & CSS class
<form action=quot;/entries/1quot;   class=quot;edit_entryquot;
     id=quot;edit_entry_1quot;      method=quot;postquot;>


• CSS class ”        AR                 ”

• ID ” AR                     _ DB ID              ”

 •           prefix             ”edit”              ”new”



 •   class    ID            dom_class() dom_id()
d
    re min            form_for()
             remembers the object.

•              FormBuilder


         <% form_for(@entry) do |f| %>
           <label>Title</label>
           <%= f.text_field :title %>
         <% end %>
ActionView::
          FormBuilder#label
• label(method,    text=nil, options={})


<% form_for(:entry,
            :url=>{:action=>”crate”}) do |f| %>
  <%= f.label :title, “       ” %>
  <%= f.text_field :title %>
<% end %>

...
<label for=”entry_title”>      <label>
...
form_for()
understands the object’s status.
<form action=quot;/entries/1quot; class=quot;edit_entryquot;
  id=quot;edit_entry_1quot; method=quot;postquot;>

  <input name=quot;_methodquot; type=quot;hiddenquot; value=quot;putquot; />
  ...
</form>


• AR

•                      POST /entries
    PUT /entries/:id
bigger

    Convention for CRUD

• HTTP              CRUD     Convention
          RFC2616

• Rails
on RubyKaigi2006,

                  DHH said
 GET              POST                  PUT               DELETE


 find             create               update               destroy


SELECT          INSERT              UPDATE                DELETE


       http://media.rubyonrails.org/presentations/worldofresources.pdf
HTTP methods and actions
GET      /entries/:id
{:controller=>quot;entriesquot;, :action=>quot;showquot;}


PUT      /entries/:id
{:controller=>quot;entriesquot;, :action=>quot;updatequot;}


DELETE   /entries/:id
{:controller=>quot;entriesquot;, :action=>quot;destroyquot;}


POST      /entries
{:controller=>quot;entriesquot;, :action=>quot;createquot;}
HTTP Method                 !
HTTP Method
               !
                          CRUD
ActiveRecord                    !
ActiveRecord                DB CRUD !!

    DB CRUD              form_for
resource oriented form              ....


HTTP               CRUD
class EntriesController < ApplicationController
  def show
    @entry = Entry.find(params[:id])
  end

  def create
    @entry = Entry.new(params[:entry])
    @entry.save
  end

  def update
    @entry = Entry.find(params[:id])
    @entry.update_attributes(params[:entry])
  end

  def destroy
    @entry = Entry.find(params[:id])
    @entry.destroy
  end
end
class EntriesController < ApplicationController
  def show
    @entry = Entry.find(params[:id])
  end

  def create
    @entry = Entry.new(params[:entry])
    @entry.save
def show
  end

  @entry = Entry.find(params[:id])
  def update
end @entry = Entry.find(params[:id])
    @entry.update_attributes(params[:entry])
  end

  def destroy
    @entry = Entry.find(params[:id])
    @entry.destroy
  end
end
class EntriesController < ApplicationController
    def show
      @entry = Entry.find(params[:id])
    end

       def create
         @entry = Entry.new(params[:entry])
         @entry.save
def    create
       end
      @entry = Entry.new(params[:entry])
      @entry.save
       def update
         @entry = Entry.find(params[:id])
end
         @entry.update_attributes(params[:entry])
       end

    def destroy
      @entry = Entry.find(params[:id])
      @entry.destroy
    end
  end
class EntriesController < ApplicationController
    def show
      @entry = Entry.find(params[:id])
    end

    def create
      @entry = Entry.new(params[:entry])
      @entry.save
def update
    end
  @entry = Entry.find(params[:id])
  @entry.update_attributes(params[:entry])
    def update
      @entry = Entry.find(params[:id])
end
      @entry.update_attributes(params[:entry])
    end

    def destroy
      @entry = Entry.find(params[:id])
      @entry.destroy
    end
  end
class EntriesController < ApplicationController
    def show
      @entry = Entry.find(params[:id])
    end

    def create
      @entry = Entry.new(params[:entry])
      @entry.save
def destroy
    end
  @entry = Entry.find(params[:id])
  @entry.destroy
    def update
      @entry = Entry.find(params[:id])
end
      @entry.update_attributes(params[:entry])
    end

    def destroy
      @entry = Entry.find(params[:id])
      @entry.destroy
    end
  end
FYI: about PUT and DELETE
•            PUT



 • POST
 • _method
<form action=quot;/entries/1quot; class=quot;edit_entryquot;
  id=quot;edit_entry_1quot; method=quot;postquot;>

  <input name=quot;_methodquot; type=quot;hiddenquot; value=quot;putquot; />
  ...
</form>
rem
           ind    I’ve talked about
features of form_for()w/ Rails 2.0
•                                 form DOM ID
      CSS

•
    FormBuilder

•
One more
(sad) thing..
Good bye end_form_tag()




                       iabl e or
               cal var
        ned lo             ag’
  un defi          _for m_t
         od `end
    meth
Conclusion
the Goal
entry =
  Entry.new(params[:entry])

entry.save()
Where         form_for()   and


  AC::Resource          going to?

• Web                    CRUD

 •

• relationship   CRUD

 • has_many :through
Conclusion of
          Conclusions
•Rails 2.0 form_for()

•AC::Resources
•Rails           blog   2.0
                          !!

•     &
Any
Question?
FAQ:
     ActiveResource               ?            ?

• RESTful        Web
                                       ARes

• Rails                ActionController ARes


 •   ActionController::Resouces

 •
FAQ:             +
                         ?

•        Rails 1.2

• DOM ID

•          1.2       URL
FAQ:
        form_for()                     ?

• config/routes.rb     resource

 •map.resources      resource_plural

• new_record?                  id

•                         AR

 •            aggregate


•↑   Array       Hash
FAQ:               ?
               1


• AR::Base.new()
 •                 OK

 •
 •                          :- )
FAQ:                                    ?
                    1
class Entry < ActiveRecord::Base
  has_many :tags

 def tags_string=(str)
   str.split(“,”).each{ ... }
 end

  def tags_string
    ts = self.tags
    ts.map(&:name).join(“, “)      entry[tags_string]
  end
end
References
• Rails                               (         )

• RESTful Web
 •   http://amazon.jp/o/ASIN/4873113539/morodiary05-22


• Discover of World of resource.
 •   http://media.rubyonrails.org/presentations/worldofresources.pdf


• RFC2616(                        )
 •   http://www.studyinghttp.net/cgi-bin/rfc.cgi?2616


• HTML 4.01 Specification(ja)
 •   http://www.asahi-net.or.jp/%7Esd5a-ucd/rec-html401j/cover.html
Epilogue
REST and Rails

• HTTP                 CRUD



• form_for()    HTML
           UI
handling
    nested resouce

•               CRUD

•    (id=2)      (id=5)

•    (id=2)
2 ways for handling nested resource

           Ordinary style
•                              blog_id


<form action=quot;/entriesquot; class=quot;new_entryquot;
      id=quot;new_entryquot; method=quot;postquot;>

    <input type=”hidden” name=”blog_id” value=”2” />
    <input type=”text” name=”entry[title]” />
    ...
</form>
2 ways for handling nested resource

     AC::Resources style
• URL
# config/routes.rb

map.resources :blog, :has_many=>:entries


# in app/views/entries/*.html.erb
form_for(@entry,:url=>blog_entries_path(@entry.blog) )


# in HTML
<form action=”/blogs/1/entries” method=”POST”>
2 ways for handling nested resource

     AC::Resources style
•
# http://exapmle.com/entries
@entries = Entry.entries.find(:all)


# http://exapmle.com/users/1/entries
@user = User.find(params[:user_id])
@entries = @user.entries.find(:all)

# http://exapmle.com/blogs/1/entries
@blog = Blog.find(params[:blog_id])
@entries = @blog.entries.find(:all)
form_for()         and REST
• HTTP is next TCP/IP
 •       TCP

 •             HTTP

• Man Machine Interface
 •
 •         Web             REST
Man Machine Interface
         and REST
•                    Human Interface

 • iPhone      NintendoDS

 •            Mac   Windows

• Web
                     REST

• Rails 2.0

More Related Content

What's hot

Zend_Form to the Rescue - A Brief Introduction to Zend_Form
Zend_Form to the Rescue - A Brief Introduction to Zend_FormZend_Form to the Rescue - A Brief Introduction to Zend_Form
Zend_Form to the Rescue - A Brief Introduction to Zend_FormJeremy Kendall
 
Symfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologyDaniel Knell
 
Internet programming lab manual
Internet programming lab manualInternet programming lab manual
Internet programming lab manualinteldualcore
 
Refactoring in Practice - Sunnyconf 2010
Refactoring in Practice - Sunnyconf 2010Refactoring in Practice - Sunnyconf 2010
Refactoring in Practice - Sunnyconf 2010Alex Sharp
 
AngularJS vs. Ember.js vs. Backbone.js
AngularJS vs. Ember.js vs. Backbone.jsAngularJS vs. Ember.js vs. Backbone.js
AngularJS vs. Ember.js vs. Backbone.jsMark
 
Dig Deeper into WordPress - WD Meetup Cairo
Dig Deeper into WordPress - WD Meetup CairoDig Deeper into WordPress - WD Meetup Cairo
Dig Deeper into WordPress - WD Meetup CairoMohamed Mosaad
 
Creating GUI Component APIs in Angular and Web Components
Creating GUI Component APIs in Angular and Web ComponentsCreating GUI Component APIs in Angular and Web Components
Creating GUI Component APIs in Angular and Web ComponentsRachael L Moore
 
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
 
Ruby on Rails For Java Programmers
Ruby on Rails For Java ProgrammersRuby on Rails For Java Programmers
Ruby on Rails For Java Programmerselliando dias
 
Tips for using Firebird system tables
Tips for using Firebird system tablesTips for using Firebird system tables
Tips for using Firebird system tablesMind The Firebird
 
Creating GUI container components in Angular and Web Components
Creating GUI container components in Angular and Web ComponentsCreating GUI container components in Angular and Web Components
Creating GUI container components in Angular and Web ComponentsRachael L Moore
 
Bag Of Tricks From Iusethis
Bag Of Tricks From IusethisBag Of Tricks From Iusethis
Bag Of Tricks From IusethisMarcus Ramberg
 
Disregard Inputs, Acquire Zend_Form
Disregard Inputs, Acquire Zend_FormDisregard Inputs, Acquire Zend_Form
Disregard Inputs, Acquire Zend_FormDaniel Cousineau
 
ZG PHP - Specification
ZG PHP - SpecificationZG PHP - Specification
ZG PHP - SpecificationRobert Šorn
 
Introduction to Zend Framework web services
Introduction to Zend Framework web servicesIntroduction to Zend Framework web services
Introduction to Zend Framework web servicesMichelangelo van Dam
 
Seaside - Web Development As You Like It
Seaside - Web Development As You Like ItSeaside - Web Development As You Like It
Seaside - Web Development As You Like ItLukas Renggli
 

What's hot (20)

Zend_Form to the Rescue - A Brief Introduction to Zend_Form
Zend_Form to the Rescue - A Brief Introduction to Zend_FormZend_Form to the Rescue - A Brief Introduction to Zend_Form
Zend_Form to the Rescue - A Brief Introduction to Zend_Form
 
Symfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technology
 
Internet programming lab manual
Internet programming lab manualInternet programming lab manual
Internet programming lab manual
 
Zend framework 04 - forms
Zend framework 04 - formsZend framework 04 - forms
Zend framework 04 - forms
 
Backbone - TDC 2011 Floripa
Backbone - TDC 2011 FloripaBackbone - TDC 2011 Floripa
Backbone - TDC 2011 Floripa
 
Refactoring in Practice - Sunnyconf 2010
Refactoring in Practice - Sunnyconf 2010Refactoring in Practice - Sunnyconf 2010
Refactoring in Practice - Sunnyconf 2010
 
AngularJS vs. Ember.js vs. Backbone.js
AngularJS vs. Ember.js vs. Backbone.jsAngularJS vs. Ember.js vs. Backbone.js
AngularJS vs. Ember.js vs. Backbone.js
 
Dig Deeper into WordPress - WD Meetup Cairo
Dig Deeper into WordPress - WD Meetup CairoDig Deeper into WordPress - WD Meetup Cairo
Dig Deeper into WordPress - WD Meetup Cairo
 
Creating GUI Component APIs in Angular and Web Components
Creating GUI Component APIs in Angular and Web ComponentsCreating GUI Component APIs in Angular and Web Components
Creating GUI Component APIs in Angular and Web Components
 
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
 
Ruby on Rails For Java Programmers
Ruby on Rails For Java ProgrammersRuby on Rails For Java Programmers
Ruby on Rails For Java Programmers
 
Tips for using Firebird system tables
Tips for using Firebird system tablesTips for using Firebird system tables
Tips for using Firebird system tables
 
Leveraging Symfony2 Forms
Leveraging Symfony2 FormsLeveraging Symfony2 Forms
Leveraging Symfony2 Forms
 
Creating GUI container components in Angular and Web Components
Creating GUI container components in Angular and Web ComponentsCreating GUI container components in Angular and Web Components
Creating GUI container components in Angular and Web Components
 
Bag Of Tricks From Iusethis
Bag Of Tricks From IusethisBag Of Tricks From Iusethis
Bag Of Tricks From Iusethis
 
Disregard Inputs, Acquire Zend_Form
Disregard Inputs, Acquire Zend_FormDisregard Inputs, Acquire Zend_Form
Disregard Inputs, Acquire Zend_Form
 
ZG PHP - Specification
ZG PHP - SpecificationZG PHP - Specification
ZG PHP - Specification
 
Polymer
PolymerPolymer
Polymer
 
Introduction to Zend Framework web services
Introduction to Zend Framework web servicesIntroduction to Zend Framework web services
Introduction to Zend Framework web services
 
Seaside - Web Development As You Like It
Seaside - Web Development As You Like ItSeaside - Web Development As You Like It
Seaside - Web Development As You Like It
 

Viewers also liked

Capistrano in practice - WebCareer
Capistrano in practice - WebCareerCapistrano in practice - WebCareer
Capistrano in practice - WebCareerKyosuke MOROHASHI
 
OSC2008 勉強会大集合 Rails勉強会@東京
OSC2008 勉強会大集合 Rails勉強会@東京OSC2008 勉強会大集合 Rails勉強会@東京
OSC2008 勉強会大集合 Rails勉強会@東京Kyosuke MOROHASHI
 
Test Context Arrangement Recipebook
Test Context Arrangement RecipebookTest Context Arrangement Recipebook
Test Context Arrangement RecipebookKyosuke MOROHASHI
 
SWID Tag Creation Tool
SWID Tag Creation Tool SWID Tag Creation Tool
SWID Tag Creation Tool Dj Das
 
そうだ勉強会に行こう
そうだ勉強会に行こうそうだ勉強会に行こう
そうだ勉強会に行こうKyosuke MOROHASHI
 

Viewers also liked (6)

Capistrano in practice - WebCareer
Capistrano in practice - WebCareerCapistrano in practice - WebCareer
Capistrano in practice - WebCareer
 
OSC2008 勉強会大集合 Rails勉強会@東京
OSC2008 勉強会大集合 Rails勉強会@東京OSC2008 勉強会大集合 Rails勉強会@東京
OSC2008 勉強会大集合 Rails勉強会@東京
 
Rails Tokyo 035 Cucumber
Rails Tokyo 035 CucumberRails Tokyo 035 Cucumber
Rails Tokyo 035 Cucumber
 
Test Context Arrangement Recipebook
Test Context Arrangement RecipebookTest Context Arrangement Recipebook
Test Context Arrangement Recipebook
 
SWID Tag Creation Tool
SWID Tag Creation Tool SWID Tag Creation Tool
SWID Tag Creation Tool
 
そうだ勉強会に行こう
そうだ勉強会に行こうそうだ勉強会に行こう
そうだ勉強会に行こう
 

Similar to Rails <form> Chronicle

Rails GUI Development with Ext JS
Rails GUI Development with Ext JSRails GUI Development with Ext JS
Rails GUI Development with Ext JSMartin Rehfeld
 
REST and AJAX Reconciled
REST and AJAX ReconciledREST and AJAX Reconciled
REST and AJAX ReconciledLars Trieloff
 
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 2RORLAB
 
JavaScript on Rails 튜토리얼
JavaScript on Rails 튜토리얼JavaScript on Rails 튜토리얼
JavaScript on Rails 튜토리얼Sukjoon Kim
 
Rails 3 overview
Rails 3 overviewRails 3 overview
Rails 3 overviewYehuda Katz
 
ActiveResource & REST
ActiveResource & RESTActiveResource & REST
ActiveResource & RESTRobbert
 
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
 
Your Custom WordPress Admin Pages Suck
Your Custom WordPress Admin Pages SuckYour Custom WordPress Admin Pages Suck
Your Custom WordPress Admin Pages SuckAnthony Montalbano
 
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
 
Rails 3: Dashing to the Finish
Rails 3: Dashing to the FinishRails 3: Dashing to the Finish
Rails 3: Dashing to the FinishYehuda Katz
 
Implementation of GUI Framework part3
Implementation of GUI Framework part3Implementation of GUI Framework part3
Implementation of GUI Framework part3masahiroookubo
 
[DSBW Spring 2009] Unit 07: WebApp Design Patterns & Frameworks (3/3)
[DSBW Spring 2009] Unit 07: WebApp Design Patterns & Frameworks (3/3)[DSBW Spring 2009] Unit 07: WebApp Design Patterns & Frameworks (3/3)
[DSBW Spring 2009] Unit 07: WebApp Design Patterns & Frameworks (3/3)Carles Farré
 
Introduction to Active Record at MySQL Conference 2007
Introduction to Active Record at MySQL Conference 2007Introduction to Active Record at MySQL Conference 2007
Introduction to Active Record at MySQL Conference 2007Rabble .
 
浜松Rails3道場 其の壱 プロジェクト作成〜Rouging編
浜松Rails3道場 其の壱 プロジェクト作成〜Rouging編浜松Rails3道場 其の壱 プロジェクト作成〜Rouging編
浜松Rails3道場 其の壱 プロジェクト作成〜Rouging編Masakuni Kato
 
Boston Computing Review - Ruby on Rails
Boston Computing Review - Ruby on RailsBoston Computing Review - Ruby on Rails
Boston Computing Review - Ruby on RailsJohn Brunswick
 
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
 
OSDC 2009 Rails Turtorial
OSDC 2009 Rails TurtorialOSDC 2009 Rails Turtorial
OSDC 2009 Rails TurtorialYi-Ting Cheng
 

Similar to Rails <form> Chronicle (20)

Rails GUI Development with Ext JS
Rails GUI Development with Ext JSRails GUI Development with Ext JS
Rails GUI Development with Ext JS
 
Framework
FrameworkFramework
Framework
 
REST and AJAX Reconciled
REST and AJAX ReconciledREST and AJAX Reconciled
REST and AJAX Reconciled
 
JS-05-Handlebars.ppt
JS-05-Handlebars.pptJS-05-Handlebars.ppt
JS-05-Handlebars.ppt
 
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
 
JavaScript on Rails 튜토리얼
JavaScript on Rails 튜토리얼JavaScript on Rails 튜토리얼
JavaScript on Rails 튜토리얼
 
Rails 3 overview
Rails 3 overviewRails 3 overview
Rails 3 overview
 
ActiveResource & REST
ActiveResource & RESTActiveResource & REST
ActiveResource & REST
 
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
 
Your Custom WordPress Admin Pages Suck
Your Custom WordPress Admin Pages SuckYour Custom WordPress Admin Pages Suck
Your Custom WordPress Admin Pages Suck
 
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
 
Rails 3: Dashing to the Finish
Rails 3: Dashing to the FinishRails 3: Dashing to the Finish
Rails 3: Dashing to the Finish
 
Implementation of GUI Framework part3
Implementation of GUI Framework part3Implementation of GUI Framework part3
Implementation of GUI Framework part3
 
[DSBW Spring 2009] Unit 07: WebApp Design Patterns & Frameworks (3/3)
[DSBW Spring 2009] Unit 07: WebApp Design Patterns & Frameworks (3/3)[DSBW Spring 2009] Unit 07: WebApp Design Patterns & Frameworks (3/3)
[DSBW Spring 2009] Unit 07: WebApp Design Patterns & Frameworks (3/3)
 
Introduction to Active Record at MySQL Conference 2007
Introduction to Active Record at MySQL Conference 2007Introduction to Active Record at MySQL Conference 2007
Introduction to Active Record at MySQL Conference 2007
 
浜松Rails3道場 其の壱 プロジェクト作成〜Rouging編
浜松Rails3道場 其の壱 プロジェクト作成〜Rouging編浜松Rails3道場 其の壱 プロジェクト作成〜Rouging編
浜松Rails3道場 其の壱 プロジェクト作成〜Rouging編
 
Boston Computing Review - Ruby on Rails
Boston Computing Review - Ruby on RailsBoston Computing Review - Ruby on Rails
Boston Computing Review - Ruby on Rails
 
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
 
JSP
JSPJSP
JSP
 
OSDC 2009 Rails Turtorial
OSDC 2009 Rails TurtorialOSDC 2009 Rails Turtorial
OSDC 2009 Rails Turtorial
 

More from Kyosuke MOROHASHI

Ruby ecosystem applied to agile project
Ruby ecosystem applied to agile projectRuby ecosystem applied to agile project
Ruby ecosystem applied to agile projectKyosuke MOROHASHI
 
Begin cucumber-in-real-world
Begin cucumber-in-real-worldBegin cucumber-in-real-world
Begin cucumber-in-real-worldKyosuke MOROHASHI
 
Rails testing environment, 2009 fall
Rails testing environment, 2009 fallRails testing environment, 2009 fall
Rails testing environment, 2009 fallKyosuke MOROHASHI
 
TDD frameworks let me dream "Project Specific Language"
TDD frameworks let me dream "Project Specific Language"TDD frameworks let me dream "Project Specific Language"
TDD frameworks let me dream "Project Specific Language"Kyosuke MOROHASHI
 
named_scope more detail - WebCareer
named_scope more detail - WebCareernamed_scope more detail - WebCareer
named_scope more detail - WebCareerKyosuke MOROHASHI
 

More from Kyosuke MOROHASHI (8)

Introduction HTTP via cURL
Introduction HTTP via cURLIntroduction HTTP via cURL
Introduction HTTP via cURL
 
Ruby ecosystem applied to agile project
Ruby ecosystem applied to agile projectRuby ecosystem applied to agile project
Ruby ecosystem applied to agile project
 
Begin cucumber-in-real-world
Begin cucumber-in-real-worldBegin cucumber-in-real-world
Begin cucumber-in-real-world
 
Cucumber in Practice(en)
Cucumber in Practice(en)Cucumber in Practice(en)
Cucumber in Practice(en)
 
Rails testing environment, 2009 fall
Rails testing environment, 2009 fallRails testing environment, 2009 fall
Rails testing environment, 2009 fall
 
TDD frameworks let me dream "Project Specific Language"
TDD frameworks let me dream "Project Specific Language"TDD frameworks let me dream "Project Specific Language"
TDD frameworks let me dream "Project Specific Language"
 
named_scope more detail - WebCareer
named_scope more detail - WebCareernamed_scope more detail - WebCareer
named_scope more detail - WebCareer
 
named_scope more detail
named_scope more detailnamed_scope more detail
named_scope more detail
 

Recently uploaded

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 

Recently uploaded (20)

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 

Rails <form> Chronicle

  • 1. Rails <form> Chronicle history of “name” attribute and form_* helper methods. 2008 / 2 / 16 PostgreSQL / Ruby / Rails @
  • 2. •( ) • Ruby Rails • Rails @ •
  • 3. Acknowledgments • • PostgreSQL / Ruby • • •Rails @ •
  • 5. ( ) Rails • Rails • Ruby
  • 6. Contact me •k-morohashi@esm.co.jp (work) •moronatural@gmail.com (private) •http://d.hatena.ne.jp/moro/ • :- )
  • 7. blog FeedList http://feedlist.net/
  • 8.
  • 9. Conclusion • / # in app/controllers/entries_controller.rb entry = Entry.new(params[:entry]) • •form
  • 11. <form> is an HTML element. • form • HTTP <form id=”new_entry” action=”/entries” method=”POST”> <label for=”entry_title”>Title</label> <input type=”text” id=”entry_title” name=”entry[title]” /> <label for=”entry_body”>Body</label> <textarea id=”entry_body” name=”entry[body]”></textarea> </form>
  • 12. <form> is an Interface. • User Interface.
  • 13. <form> has some Controls. • Control (input or so) • Control name <form id=”new_entry” action=”/entries” method=”POST”> <label for=”entry_title”>Title</label> <input type=”text” id=”entry_title” name=”entry[title]” /> <label for=”entry_body”>Body</label> <textarea id=”entry_body” name=”entry[body]”> </textarea> </form>
  • 14. What is control’s “name” attribute. • name • • “name”
  • 15. “name” attribute is the Programming Interface • form API ! • name API ! • action method
  • 16. <form> is an Interface. • User Interface • Programing Interface
  • 17. How does Rails handle?
  • 18. Phase 1 From View to Controller
  • 19. Rails handle query parameters like a Hash •Rails Hash POST /entry entry[title]=new title&entry[body]=new body params() # =>{ :entry => {:title => “new title”, :body => ”new body”}}
  • 20. Examples <form action=”...”> <input name=”title” type=”text” /> <input name=”body” type=”text” /> </form> {:title => “new title”, :body => ”new body”}
  • 21. Examples <form action=”...”> <input name=”entry[title]” type=”text” /> <input name=”entry[body]” type=”text” /> </form> { :entry => {:title => “new title”, :body => ”new body” }}
  • 22. Examples <form action=quot;...quot;> <input type=quot;textquot; name=quot;entry[title]quot; /> <input type=quot;textquot; name=quot;entry[links][]quot; /> <input type=quot;textquot; name=quot;entry[links][]quot; /> <input type=quot;textquot; name=quot;entry[links][]quot; /> </form> {quot;entryquot;=>{quot;titlequot;=>quot;aaaquot;, quot;linksquot;=>[quot;xxxquot;, quot;yyyquot;, quot;zzzquot;]}}
  • 23. Phase 2 From Controller to Model (and DB)
  • 24. Rails handle Hash as AR constructor argument. • Rails Hash ActiveRecord hash = { :entry => {:title => “new title”, :body => ”new body”}} entry = Entry.new(hash[:entry]) entry.title # => “new title”
  • 25. And, of course, Rails can save AR object to DB • Rails ActiveRecord DB entry = Entry.new(hash) entry.title # => “new title” entry.save
  • 26. Therefore Rails can save form-data to DB at ease. • Rails form DB entry = Entry.new(params[:entry]) entry.save
  • 27. In other words, entry = Entry.new(params[:entry]) • params[ ] • form name
  • 28. Rails <form> Chronicle history of “name” attribute and form_* helper methods.
  • 29. ~ Rails 1.0 Before form_for()
  • 30. form_tag(url_for_options = {}, options = {}, *parameters_for_url) • Rails 1.0 <form> • HTML form • action url_for_options • options
  • 31. Thin wrapper for HTML <form> tag. form_tag( {:controller=>”entries”,:action=>”create”}, {:id=>”new_entry”, :method=>”post”} ) generates <form id=”new_entry” method=”POST” action=>”entries/create”>
  • 32. and there is lovely end_form_tag() # Outputs “</form>” def end_form_tag “</form>” end
  • 33. ActionView::Helpers:: FormHelper. • FormHelper !! @entry = Entry.new(:title=>” ”) text_field(:entry, :title) # => <input type=”text” name=”entry[title]” value=” ” /> • ActiveRecord (=DB ) form
  • 34. ActionView::Helpers:: FormHelper. @entry = Entry.new(:title=>” ”) text_field(:entry, :title) # => <input type=”text” name=”entry[title]” value=” ” /> and you will get {:entry => {:title => “ ” }}
  • 35. ActionView::Helpers:: FormHelper. text_field(object, method, options={}) • object ”@#{object}” • method • “#{object}[#{name}]” name input
  • 36. rem ind Examples <form action=”...”> <input name=”entry[title]” type=”text” /> <input name=”entry[body]” type=”text” /> </form> { :entry => {:title => “new title”, :body => ”new body” }}
  • 37. Rails 1.1& Rails1.2 form_for() has come.
  • 38. form_for( object_name, *args, &proc) • Rails 1.1 • • URL • • “Creates a form and a scope around a specific model object, ”(from API Document)
  • 39. form for the object. • • text_field() • == <%# @entry %> <% form_for(:entry, :url=>{:action=>”crate”}) do |f| %> ... <% end %>
  • 40. form_for() remembers the object. • ActionView::FormBuilder • text_field(method, options={}) • cf : text_field(object, method, options={}) in Rails 1.0 <% form_for(:entry, :url=>{:action=>”crate”}) do |f| %> # @entry#title text field <label>Title</label> <%= f.text_field :title %> <% end %>
  • 41. ActionView:: FormBuilder <% form_for(:entry, :url=>{:action=>”crate”}) do |f| %> <label>Title</label> <%= f.text_field :title %> <% end %> generates <form action=quot;/entries/createquot; method=quot;postquot;> <label>Title</label> <input id=quot;entry_titlequot; name=quot;entry[title]quot; size=quot;30quot; type=quot;textquot; /> </form>
  • 42. FYI: 2nd argument. • <% entry_local = Entry.new(:title=>”local”) %> <% form_for(:entry, entry_local, :url=>{:action=>”crate”}) do |f| %> <label>Title</label> <%= f.text_field :title %> <% end %> • respond_to?(:title) OK
  • 43. OK, but Why form_for()? rem i nd • Rails Hash re min d • “Creates a form and a scope around a specific model object, ” • CRUD HTML • ↑↑
  • 44. OK, but Does it works well? • has_many :through • CRUD • RDBMS
  • 45. But... • form_for (Rails @ ) • • end_form_tag() obsolete • (?) •
  • 47. form_for() and map.resource • AR ”resource” •“resource” HTTP CRUD ActionController::Routes.draw do |m| map.resources :entries end
  • 48. new form_for() <% @entry = Entry.find(1) %> <% form_for(@entry) do |f|%> ... <% end %> generates <form action=quot;/entries/1quot; class=quot;edit_entryquot; id=quot;edit_entry_1quot; method=quot;postquot;> <input name=quot;_methodquot; type=quot;hiddenquot; value=quot;putquot; /> ... </form>
  • 49. form_for() determine the form identity. <form action=quot;/entries/1quot; class=quot;edit_entryquot; id=quot;edit_entry_1quot; method=quot;postquot;> <input name=quot;_methodquot; type=quot;hiddenquot; value=quot;putquot; /> ... </form> • ActiveRecord Convention • class ID
  • 50. new Convention for DOM ID & CSS class <form action=quot;/entries/1quot; class=quot;edit_entryquot; id=quot;edit_entry_1quot; method=quot;postquot;> • CSS class ” AR ” • ID ” AR _ DB ID ” • prefix ”edit” ”new” • class ID dom_class() dom_id()
  • 51. d re min form_for() remembers the object. • FormBuilder <% form_for(@entry) do |f| %> <label>Title</label> <%= f.text_field :title %> <% end %>
  • 52. ActionView:: FormBuilder#label • label(method, text=nil, options={}) <% form_for(:entry, :url=>{:action=>”crate”}) do |f| %> <%= f.label :title, “ ” %> <%= f.text_field :title %> <% end %> ... <label for=”entry_title”> <label> ...
  • 53. form_for() understands the object’s status. <form action=quot;/entries/1quot; class=quot;edit_entryquot; id=quot;edit_entry_1quot; method=quot;postquot;> <input name=quot;_methodquot; type=quot;hiddenquot; value=quot;putquot; /> ... </form> • AR • POST /entries PUT /entries/:id
  • 54. bigger Convention for CRUD • HTTP CRUD Convention RFC2616 • Rails
  • 55. on RubyKaigi2006, DHH said GET POST PUT DELETE find create update destroy SELECT INSERT UPDATE DELETE http://media.rubyonrails.org/presentations/worldofresources.pdf
  • 56. HTTP methods and actions GET /entries/:id {:controller=>quot;entriesquot;, :action=>quot;showquot;} PUT /entries/:id {:controller=>quot;entriesquot;, :action=>quot;updatequot;} DELETE /entries/:id {:controller=>quot;entriesquot;, :action=>quot;destroyquot;} POST /entries {:controller=>quot;entriesquot;, :action=>quot;createquot;}
  • 57. HTTP Method ! HTTP Method ! CRUD ActiveRecord ! ActiveRecord DB CRUD !! DB CRUD form_for resource oriented form .... HTTP CRUD
  • 58.
  • 59. class EntriesController < ApplicationController def show @entry = Entry.find(params[:id]) end def create @entry = Entry.new(params[:entry]) @entry.save end def update @entry = Entry.find(params[:id]) @entry.update_attributes(params[:entry]) end def destroy @entry = Entry.find(params[:id]) @entry.destroy end end
  • 60. class EntriesController < ApplicationController def show @entry = Entry.find(params[:id]) end def create @entry = Entry.new(params[:entry]) @entry.save def show end @entry = Entry.find(params[:id]) def update end @entry = Entry.find(params[:id]) @entry.update_attributes(params[:entry]) end def destroy @entry = Entry.find(params[:id]) @entry.destroy end end
  • 61. class EntriesController < ApplicationController def show @entry = Entry.find(params[:id]) end def create @entry = Entry.new(params[:entry]) @entry.save def create end @entry = Entry.new(params[:entry]) @entry.save def update @entry = Entry.find(params[:id]) end @entry.update_attributes(params[:entry]) end def destroy @entry = Entry.find(params[:id]) @entry.destroy end end
  • 62. class EntriesController < ApplicationController def show @entry = Entry.find(params[:id]) end def create @entry = Entry.new(params[:entry]) @entry.save def update end @entry = Entry.find(params[:id]) @entry.update_attributes(params[:entry]) def update @entry = Entry.find(params[:id]) end @entry.update_attributes(params[:entry]) end def destroy @entry = Entry.find(params[:id]) @entry.destroy end end
  • 63. class EntriesController < ApplicationController def show @entry = Entry.find(params[:id]) end def create @entry = Entry.new(params[:entry]) @entry.save def destroy end @entry = Entry.find(params[:id]) @entry.destroy def update @entry = Entry.find(params[:id]) end @entry.update_attributes(params[:entry]) end def destroy @entry = Entry.find(params[:id]) @entry.destroy end end
  • 64. FYI: about PUT and DELETE • PUT • POST • _method <form action=quot;/entries/1quot; class=quot;edit_entryquot; id=quot;edit_entry_1quot; method=quot;postquot;> <input name=quot;_methodquot; type=quot;hiddenquot; value=quot;putquot; /> ... </form>
  • 65. rem ind I’ve talked about features of form_for()w/ Rails 2.0 • form DOM ID CSS • FormBuilder •
  • 67. Good bye end_form_tag() iabl e or cal var ned lo ag’ un defi _for m_t od `end meth
  • 69. the Goal entry = Entry.new(params[:entry]) entry.save()
  • 70. Where form_for() and AC::Resource going to? • Web CRUD • • relationship CRUD • has_many :through
  • 71. Conclusion of Conclusions •Rails 2.0 form_for() •AC::Resources •Rails blog 2.0 !! • &
  • 73. FAQ: ActiveResource ? ? • RESTful Web ARes • Rails ActionController ARes • ActionController::Resouces •
  • 74. FAQ: + ? • Rails 1.2 • DOM ID • 1.2 URL
  • 75. FAQ: form_for() ? • config/routes.rb resource •map.resources resource_plural • new_record? id • AR • aggregate •↑ Array Hash
  • 76. FAQ: ? 1 • AR::Base.new() • OK • • :- )
  • 77. FAQ: ? 1 class Entry < ActiveRecord::Base has_many :tags def tags_string=(str) str.split(“,”).each{ ... } end def tags_string ts = self.tags ts.map(&:name).join(“, “) entry[tags_string] end end
  • 78.
  • 79. References • Rails ( ) • RESTful Web • http://amazon.jp/o/ASIN/4873113539/morodiary05-22 • Discover of World of resource. • http://media.rubyonrails.org/presentations/worldofresources.pdf • RFC2616( ) • http://www.studyinghttp.net/cgi-bin/rfc.cgi?2616 • HTML 4.01 Specification(ja) • http://www.asahi-net.or.jp/%7Esd5a-ucd/rec-html401j/cover.html
  • 80.
  • 82. REST and Rails • HTTP CRUD • form_for() HTML UI
  • 83. handling nested resouce • CRUD • (id=2) (id=5) • (id=2)
  • 84. 2 ways for handling nested resource Ordinary style • blog_id <form action=quot;/entriesquot; class=quot;new_entryquot; id=quot;new_entryquot; method=quot;postquot;> <input type=”hidden” name=”blog_id” value=”2” /> <input type=”text” name=”entry[title]” /> ... </form>
  • 85. 2 ways for handling nested resource AC::Resources style • URL # config/routes.rb map.resources :blog, :has_many=>:entries # in app/views/entries/*.html.erb form_for(@entry,:url=>blog_entries_path(@entry.blog) ) # in HTML <form action=”/blogs/1/entries” method=”POST”>
  • 86. 2 ways for handling nested resource AC::Resources style • # http://exapmle.com/entries @entries = Entry.entries.find(:all) # http://exapmle.com/users/1/entries @user = User.find(params[:user_id]) @entries = @user.entries.find(:all) # http://exapmle.com/blogs/1/entries @blog = Blog.find(params[:blog_id]) @entries = @blog.entries.find(:all)
  • 87. form_for() and REST • HTTP is next TCP/IP • TCP • HTTP • Man Machine Interface • • Web REST
  • 88. Man Machine Interface and REST • Human Interface • iPhone NintendoDS • Mac Windows • Web REST • Rails 2.0