SlideShare a Scribd company logo
1 of 15
ROR Lab. Season 2
   - The 4th Round -



Getting Started
 with Rails (4)

    August 11, 2012

     Hyoseong Choi
       ROR Lab.
A Blog Project

                                    Post
                              ny




                                              on
                             a
                            m
separate form                                           nested form



                                                 e
                       to          form_for




                                                to
                  ne




                                                     m
                                                      an
                 o




                                                        y
      Comment                                               Tag

      form_for                                         fields_for



                                                                   ROR Lab.
Generating the 3rd
   Model : Tag
  $ rails generate model tag
                 name:string
                 post:references


                                                  Migration file
        Model Class                     : db/migrate/xxxx_create_tag.rb
    : app/models/tag.rb

         Tag                                       tags
                          $ rake db:migrate


 belongs_to :post                        post_id :integer
  post:references
                                                              ROR Lab.
Nested Attributes
• save the child object through the parent
  object
• Off, by default
• switch “On”, by calling
  #accepts_nested_attributes_for
  •   an attribute writer automatically defined on the parent
      model
  •   :autosave option automatically enabled

  http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html


                                                                               ROR Lab.
Building a Multi-
        Model Form                                      ✔




class Post < ActiveRecord::Base
  attr_accessible :content, :name, :title, :tags_attributes

  validates :name,  :presence => true
  validates :title, :presence => true,
                    :length => { :minimum => 5 }
 
  has_many :comments, :dependent => :destroy
  has_many :tags
                                                         ✔
  accepts_nested_attributes_for :tags, :allow_destroy => :true,
    :reject_if => proc { |attrs| attrs.all? { |k, v| v.blank? } }
end                    ✔



  multi-model form or nested form or form in form
                                                                    ROR Lab.
#accepts_nested
   _attributes_for
• tags_attributes=(attributes)
• :allow_destroy => true
  “_destroy” key, evaluated to true
• :reject_if => proc { |attributes|
  attributes[‘name’].blank? }
• :reject_if => proc { |attrs| attrs.all? { |k,v|
  v.blank?} }
                                             ROR Lab.
build vs new

• new ➞ for Class
  ex) post = Post.new
• build ➞ for association proxy
  ex) comment = post.comments.build
  ✓ automatic setting its foreign key for the
    new child object with patient object id


                                         ROR Lab.
<% @post.tags.build %>
<%= form_for(@post) do |post_form| %> 
  <div class="field">
    <%= post_form.label :name %><br />
    <%= post_form.text_field :name %>
  </div>
  <div class="field">
    <%= post_form.label :title %><br />
    <%= post_form.text_field :title %>
  </div>
  <div class="field">
    <%= post_form.label :content %><br />
    <%= post_form.text_area :content %>
  </div>

  <h2>Tags</h2>
  <%= post_form.fields_for :tags do |tag_form| %>
   <div class="field">
     <%= tag_form.label :name, 'Tag:' %>
     <%= tag_form.text_field :name %>
   </div>
   <% unless tag_form.object.nil? || tag_form.object.new_record? %>
     <div class="field">
       <%= tag_form.label :_destroy, 'Remove:' %>
       <%= tag_form.check_box :_destroy %>
     </div>
   <% end %>
  <% end %>

  <div class="actions">
    <%= post_form.submit %>
  </div>
<% end %>
                                                                      ✔   app/views/posts/_form.html.erb

                                                                                             ROR Lab.
<% @post.tags.build %>
<%= form_for(@post) do |post_form| %> 
  <div class="field">
    <%= post_form.label :name %><br />
    <%= post_form.text_field :name %>
  </div>
  <div class="field">
    <%= post_form.label :title %><br />
    <%= post_form.text_field :title %>
  </div>
  <div class="field">
    <%= post_form.label :content %><br />                     accets_nested_attributes_for :tags
    <%= post_form.text_area :content %>
  </div>

  <h2>Tags</h2>
  <%= post_form.fields_for :tags do |tag_form| %>
   <div class="field">
     <%= tag_form.label :name, 'Tag:' %>
     <%= tag_form.text_field :name %>
   </div>
   <% unless tag_form.object.nil? || tag_form.object.new_record? %>
     <div class="field">
       <%= tag_form.label :_destroy, 'Remove:' %>
       <%= tag_form.check_box :_destroy %>
     </div>
   <% end %>
  <% end %>

  <div class="actions">
    <%= post_form.submit %>
  </div>
<% end %>
                                                                      ✔   app/views/posts/_form.html.erb

                                                                                               ROR Lab.
<% @post.tags.build %>
<%= form_for(@post) do |post_form| %> 
  <div class="field">
    <%= post_form.label :name %><br />
    <%= post_form.text_field :name %>
  </div>
  <div class="field">
    <%= post_form.label :title %><br />
    <%= post_form.text_field :title %>
  </div>
  <div class="field">
    <%= post_form.label :content %><br />                     accets_nested_attributes_for :tags
    <%= post_form.text_area :content %>
  </div>
                                                             tags_attributes
  <h2>Tags</h2>
  <%= post_form.fields_for :tags do |tag_form| %>
   <div class="field">
     <%= tag_form.label :name, 'Tag:' %>
     <%= tag_form.text_field :name %>
   </div>
   <% unless tag_form.object.nil? || tag_form.object.new_record? %>
     <div class="field">
       <%= tag_form.label :_destroy, 'Remove:' %>
       <%= tag_form.check_box :_destroy %>
     </div>
   <% end %>
  <% end %>

  <div class="actions">
    <%= post_form.submit %>
  </div>
<% end %>
                                                                      ✔   app/views/posts/_form.html.erb

                                                                                               ROR Lab.
<% @post.tags.build %>
<%= form_for(@post) do |post_form| %>
  <% if @post.errors.any? %>
  <div id="errorExplanation">
    <h2><%= pluralize(@post.errors.count, "error") %>   prohibited this post from being saved:</h2>
    <ul>
    <% @post.errors.full_messages.each do |msg| %>
      <li><%= msg %></li>
    <% end %>
    </ul>                                               <%= form.fields_for :tags do |tag_form| %>
  </div>                                                  <div class="field">
  <% end %>                                                 <%= tag_form.label :name, 'Tag:' %>
                                                            <%= tag_form.text_field :name %>
  <div class="field">
                                                          </div>
    <%= post_form.label :name %><br />
                                                          <% unless tag_form.object.nil? || tag_form.object.new_record? %>
    <%= post_form.text_field :name %>
                                                            <div class="field">
  </div>
                                                              <%= tag_form.label :_destroy, 'Remove:' %>
  <div class="field">
                                                              <%= tag_form.check_box :_destroy %>
    <%= post_form.label :title %><br />
                                                            </div>
    <%= post_form.text_field :title %>
                                                          <% end %>
  </div>
                                                        <% end %>
  <div class="field">                                                                          ✔ app/views/tags/_form.html.erb
    <%= post_form.label :content %><br />
    <%= post_form.text_area :content %>
  </div>
  <h2>Tags</h2>
  <%= render :partial => 'tags/form',
             :locals => {:form => post_form} %>
  <div class="actions">
    <%= post_form.submit %>
  </div>
<% end %>
                                                                          ✔   app/views/posts/_form.html.erb


                                                                                                               ROR Lab.
<p id="notice"><%= notice %></p>
 
<p>
  <b>Name:</b>
  <%= @post.name %>
</p>
 
<p>                                                   module PostsHelper
  <b>Title:</b>                                         def join_tags(post)
  <%= @post.title %>                                      post.tags.map { |t| t.name }.join(", ")
</p>                                                    end
                                                      end
<p>
  <b>Content:</b>
                                                                 ✔ app/helpers/posts_helper.rb
  <%= @post.content %>
</p>
 
<p>
                                                      <p>
  <b>Tags:</b>
                                                        <b>Tags:</b>
  <%= @post.tags.map { |t| t.name }.join(", ") %>
                                                        <%= join_tags(@post) %>
</p>
                                                      </p>
 
<h2>Comments</h2>
<%= render @post.comments %>
 
<h2>Add a comment:</h2>
<%= render "comments/form" %>
 
 
<%= link_to 'Edit Post', edit_post_path(@post) %> |
<%= link_to 'Back to Posts', posts_path %> |

                ✔ app/views/posts/show.html.erb


                                                                                            ROR Lab.
<p id="notice"><%= notice %></p>
 
<p>
  <b>Name:</b>
  <%= @post.name %>
</p>
 
<p>                                                   module PostsHelper
  <b>Title:</b>                                         def join_tags(post)
  <%= @post.title %>                                      post.tags.map { |t| t.name }.join(", ")
</p>                                                    end
                                                      end
<p>
  <b>Content:</b>
                                                                 ✔ app/helpers/posts_helper.rb
  <%= @post.content %>
</p>
 
<p>
                                                      <p>
  <b>Tags:</b>
                                                        <b>Tags:</b>
  <%= join_tags(@post) %>
                                                        <%= join_tags(@post) %>
</p>
                                                      </p>
 
<h2>Comments</h2>
<%= render @post.comments %>
 
<h2>Add a comment:</h2>
<%= render "comments/form" %>
 
 
<%= link_to 'Edit Post', edit_post_path(@post) %> |
<%= link_to 'Back to Posts', posts_path %> |

                ✔ app/views/posts/show.html.erb


                                                                                            ROR Lab.
Live Demo
Creating a project ~ 3rd model, Tag




                                      ROR Lab.
감사합니다.

More Related Content

Viewers also liked

Active Record callbacks and Observers, Season 1
Active Record callbacks and Observers, Season 1Active Record callbacks and Observers, Season 1
Active Record callbacks and Observers, Season 1RORLAB
 
Active Support Core Extensions (1)
Active Support Core Extensions (1)Active Support Core Extensions (1)
Active Support Core Extensions (1)RORLAB
 
Routing 2, Season 1
Routing 2, Season 1Routing 2, Season 1
Routing 2, Season 1RORLAB
 
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)
Getting Started with Rails (2)Getting Started with Rails (2)
Getting Started with Rails (2)RORLAB
 
ActiveRecord Association (1), Season 2
ActiveRecord Association (1), Season 2ActiveRecord Association (1), Season 2
ActiveRecord Association (1), 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
 

Viewers also liked (7)

Active Record callbacks and Observers, Season 1
Active Record callbacks and Observers, Season 1Active Record callbacks and Observers, Season 1
Active Record callbacks and Observers, Season 1
 
Active Support Core Extensions (1)
Active Support Core Extensions (1)Active Support Core Extensions (1)
Active Support Core Extensions (1)
 
Routing 2, Season 1
Routing 2, Season 1Routing 2, Season 1
Routing 2, Season 1
 
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)
Getting Started with Rails (2)Getting Started with Rails (2)
Getting Started with Rails (2)
 
ActiveRecord Association (1), Season 2
ActiveRecord Association (1), Season 2ActiveRecord Association (1), Season 2
ActiveRecord Association (1), 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
 

Similar to Getting started with Rails (4), Season 2

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
 
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
 
Action View Form Helpers - 2, Season 2
Action View Form Helpers - 2, Season 2Action View Form Helpers - 2, Season 2
Action View Form Helpers - 2, Season 2RORLAB
 
OSDC 2009 Rails Turtorial
OSDC 2009 Rails TurtorialOSDC 2009 Rails Turtorial
OSDC 2009 Rails TurtorialYi-Ting Cheng
 
Your Custom WordPress Admin Pages Suck
Your Custom WordPress Admin Pages SuckYour Custom WordPress Admin Pages Suck
Your Custom WordPress Admin Pages SuckAnthony Montalbano
 
Building a Rails Interface
Building a Rails InterfaceBuilding a Rails Interface
Building a Rails InterfaceJames Gray
 
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
 
Ajax nested form and ajax upload in rails
Ajax nested form and ajax upload in railsAjax nested form and ajax upload in rails
Ajax nested form and ajax upload in railsTse-Ching Ho
 
Desenvolvimento web com Ruby on Rails (parte 4)
Desenvolvimento web com Ruby on Rails (parte 4)Desenvolvimento web com Ruby on Rails (parte 4)
Desenvolvimento web com Ruby on Rails (parte 4)Joao Lucas Santana
 
Ruby on Rails at PROMPT ISEL '11
Ruby on Rails at PROMPT ISEL '11Ruby on Rails at PROMPT ISEL '11
Ruby on Rails at PROMPT ISEL '11Pedro Cunha
 
Desenvolvimento web com Ruby on Rails (parte 6)
Desenvolvimento web com Ruby on Rails (parte 6)Desenvolvimento web com Ruby on Rails (parte 6)
Desenvolvimento web com Ruby on Rails (parte 6)Joao Lucas Santana
 
Template-based Modular Architecture
Template-based Modular ArchitectureTemplate-based Modular Architecture
Template-based Modular Architecturegenify
 
Rails Antipatterns | Open Session with Chad Pytel
Rails Antipatterns | Open Session with Chad Pytel Rails Antipatterns | Open Session with Chad Pytel
Rails Antipatterns | Open Session with Chad Pytel Engine Yard
 
Desenvolvimento web com Ruby on Rails (parte 2)
Desenvolvimento web com Ruby on Rails (parte 2)Desenvolvimento web com Ruby on Rails (parte 2)
Desenvolvimento web com Ruby on Rails (parte 2)Joao Lucas Santana
 
Boston Computing Review - Ruby on Rails
Boston Computing Review - Ruby on RailsBoston Computing Review - Ruby on Rails
Boston Computing Review - Ruby on RailsJohn Brunswick
 
Curso Symfony - Clase 4
Curso Symfony - Clase 4Curso Symfony - Clase 4
Curso Symfony - Clase 4Javier Eguiluz
 
Curso Symfony - Clase 3
Curso Symfony - Clase 3Curso Symfony - Clase 3
Curso Symfony - Clase 3Javier Eguiluz
 
Django Forms: Best Practices, Tips, Tricks
Django Forms: Best Practices, Tips, TricksDjango Forms: Best Practices, Tips, Tricks
Django Forms: Best Practices, Tips, TricksShawn Rider
 
Web development today
Web development todayWeb development today
Web development todayHesham Amin
 

Similar to Getting started with Rails (4), Season 2 (20)

Action View Form Helpers - 1, Season 2
Action View Form Helpers - 1, Season 2Action View Form Helpers - 1, Season 2
Action View Form Helpers - 1, Season 2
 
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
 
Action View Form Helpers - 2, Season 2
Action View Form Helpers - 2, Season 2Action View Form Helpers - 2, Season 2
Action View Form Helpers - 2, Season 2
 
OSDC 2009 Rails Turtorial
OSDC 2009 Rails TurtorialOSDC 2009 Rails Turtorial
OSDC 2009 Rails Turtorial
 
Django Vs Rails
Django Vs RailsDjango Vs Rails
Django Vs Rails
 
Your Custom WordPress Admin Pages Suck
Your Custom WordPress Admin Pages SuckYour Custom WordPress Admin Pages Suck
Your Custom WordPress Admin Pages Suck
 
Building a Rails Interface
Building a Rails InterfaceBuilding a Rails Interface
Building a Rails Interface
 
Engines: Team Development on Rails (2005)
Engines: Team Development on Rails (2005)Engines: Team Development on Rails (2005)
Engines: Team Development on Rails (2005)
 
Ajax nested form and ajax upload in rails
Ajax nested form and ajax upload in railsAjax nested form and ajax upload in rails
Ajax nested form and ajax upload in rails
 
Desenvolvimento web com Ruby on Rails (parte 4)
Desenvolvimento web com Ruby on Rails (parte 4)Desenvolvimento web com Ruby on Rails (parte 4)
Desenvolvimento web com Ruby on Rails (parte 4)
 
Ruby on Rails at PROMPT ISEL '11
Ruby on Rails at PROMPT ISEL '11Ruby on Rails at PROMPT ISEL '11
Ruby on Rails at PROMPT ISEL '11
 
Desenvolvimento web com Ruby on Rails (parte 6)
Desenvolvimento web com Ruby on Rails (parte 6)Desenvolvimento web com Ruby on Rails (parte 6)
Desenvolvimento web com Ruby on Rails (parte 6)
 
Template-based Modular Architecture
Template-based Modular ArchitectureTemplate-based Modular Architecture
Template-based Modular Architecture
 
Rails Antipatterns | Open Session with Chad Pytel
Rails Antipatterns | Open Session with Chad Pytel Rails Antipatterns | Open Session with Chad Pytel
Rails Antipatterns | Open Session with Chad Pytel
 
Desenvolvimento web com Ruby on Rails (parte 2)
Desenvolvimento web com Ruby on Rails (parte 2)Desenvolvimento web com Ruby on Rails (parte 2)
Desenvolvimento web com Ruby on Rails (parte 2)
 
Boston Computing Review - Ruby on Rails
Boston Computing Review - Ruby on RailsBoston Computing Review - Ruby on Rails
Boston Computing Review - Ruby on Rails
 
Curso Symfony - Clase 4
Curso Symfony - Clase 4Curso Symfony - Clase 4
Curso Symfony - Clase 4
 
Curso Symfony - Clase 3
Curso Symfony - Clase 3Curso Symfony - Clase 3
Curso Symfony - Clase 3
 
Django Forms: Best Practices, Tips, Tricks
Django Forms: Best Practices, Tips, TricksDjango Forms: Best Practices, Tips, Tricks
Django Forms: Best Practices, Tips, Tricks
 
Web development today
Web development todayWeb development today
Web development today
 

More from RORLAB

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

More from RORLAB (20)

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

Recently uploaded

Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024Janet Corral
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
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
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
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
 
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
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 

Recently uploaded (20)

Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
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 ...
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
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
 
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
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 

Getting started with Rails (4), Season 2

  • 1. ROR Lab. Season 2 - The 4th Round - Getting Started with Rails (4) August 11, 2012 Hyoseong Choi ROR Lab.
  • 2. A Blog Project Post ny on a m separate form nested form e to form_for to ne m an o y Comment Tag form_for fields_for ROR Lab.
  • 3. Generating the 3rd Model : Tag $ rails generate model tag name:string post:references Migration file Model Class : db/migrate/xxxx_create_tag.rb : app/models/tag.rb Tag tags $ rake db:migrate belongs_to :post post_id :integer post:references ROR Lab.
  • 4. Nested Attributes • save the child object through the parent object • Off, by default • switch “On”, by calling #accepts_nested_attributes_for • an attribute writer automatically defined on the parent model • :autosave option automatically enabled http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html ROR Lab.
  • 5. Building a Multi- Model Form ✔ class Post < ActiveRecord::Base   attr_accessible :content, :name, :title, :tags_attributes   validates :name,  :presence => true   validates :title, :presence => true,                     :length => { :minimum => 5 }     has_many :comments, :dependent => :destroy   has_many :tags   ✔   accepts_nested_attributes_for :tags, :allow_destroy => :true,     :reject_if => proc { |attrs| attrs.all? { |k, v| v.blank? } } end ✔ multi-model form or nested form or form in form ROR Lab.
  • 6. #accepts_nested _attributes_for • tags_attributes=(attributes) • :allow_destroy => true “_destroy” key, evaluated to true • :reject_if => proc { |attributes| attributes[‘name’].blank? } • :reject_if => proc { |attrs| attrs.all? { |k,v| v.blank?} } ROR Lab.
  • 7. build vs new • new ➞ for Class ex) post = Post.new • build ➞ for association proxy ex) comment = post.comments.build ✓ automatic setting its foreign key for the new child object with patient object id ROR Lab.
  • 8. <% @post.tags.build %> <%= form_for(@post) do |post_form| %>    <div class="field">     <%= post_form.label :name %><br />     <%= post_form.text_field :name %>   </div>   <div class="field">     <%= post_form.label :title %><br />     <%= post_form.text_field :title %>   </div>   <div class="field">     <%= post_form.label :content %><br />     <%= post_form.text_area :content %>   </div>   <h2>Tags</h2>   <%= post_form.fields_for :tags do |tag_form| %>    <div class="field">      <%= tag_form.label :name, 'Tag:' %>      <%= tag_form.text_field :name %>    </div>    <% unless tag_form.object.nil? || tag_form.object.new_record? %>      <div class="field">        <%= tag_form.label :_destroy, 'Remove:' %>        <%= tag_form.check_box :_destroy %>      </div>    <% end %> <% end %>   <div class="actions">     <%= post_form.submit %>   </div> <% end %> ✔ app/views/posts/_form.html.erb ROR Lab.
  • 9. <% @post.tags.build %> <%= form_for(@post) do |post_form| %>    <div class="field">     <%= post_form.label :name %><br />     <%= post_form.text_field :name %>   </div>   <div class="field">     <%= post_form.label :title %><br />     <%= post_form.text_field :title %>   </div>   <div class="field">     <%= post_form.label :content %><br /> accets_nested_attributes_for :tags     <%= post_form.text_area :content %>   </div>   <h2>Tags</h2>   <%= post_form.fields_for :tags do |tag_form| %>    <div class="field">      <%= tag_form.label :name, 'Tag:' %>      <%= tag_form.text_field :name %>    </div>    <% unless tag_form.object.nil? || tag_form.object.new_record? %>      <div class="field">        <%= tag_form.label :_destroy, 'Remove:' %>        <%= tag_form.check_box :_destroy %>      </div>    <% end %> <% end %>   <div class="actions">     <%= post_form.submit %>   </div> <% end %> ✔ app/views/posts/_form.html.erb ROR Lab.
  • 10. <% @post.tags.build %> <%= form_for(@post) do |post_form| %>    <div class="field">     <%= post_form.label :name %><br />     <%= post_form.text_field :name %>   </div>   <div class="field">     <%= post_form.label :title %><br />     <%= post_form.text_field :title %>   </div>   <div class="field">     <%= post_form.label :content %><br /> accets_nested_attributes_for :tags     <%= post_form.text_area :content %>   </div> tags_attributes   <h2>Tags</h2>   <%= post_form.fields_for :tags do |tag_form| %>    <div class="field">      <%= tag_form.label :name, 'Tag:' %>      <%= tag_form.text_field :name %>    </div>    <% unless tag_form.object.nil? || tag_form.object.new_record? %>      <div class="field">        <%= tag_form.label :_destroy, 'Remove:' %>        <%= tag_form.check_box :_destroy %>      </div>    <% end %> <% end %>   <div class="actions">     <%= post_form.submit %>   </div> <% end %> ✔ app/views/posts/_form.html.erb ROR Lab.
  • 11. <% @post.tags.build %> <%= form_for(@post) do |post_form| %>   <% if @post.errors.any? %>   <div id="errorExplanation">     <h2><%= pluralize(@post.errors.count, "error") %> prohibited this post from being saved:</h2>     <ul>     <% @post.errors.full_messages.each do |msg| %>       <li><%= msg %></li>     <% end %>     </ul> <%= form.fields_for :tags do |tag_form| %>   </div>   <div class="field">   <% end %>     <%= tag_form.label :name, 'Tag:' %>       <%= tag_form.text_field :name %>   <div class="field">   </div>     <%= post_form.label :name %><br />   <% unless tag_form.object.nil? || tag_form.object.new_record? %>     <%= post_form.text_field :name %>     <div class="field">   </div>       <%= tag_form.label :_destroy, 'Remove:' %>   <div class="field">       <%= tag_form.check_box :_destroy %>     <%= post_form.label :title %><br />     </div>     <%= post_form.text_field :title %>   <% end %>   </div> <% end %>   <div class="field"> ✔ app/views/tags/_form.html.erb     <%= post_form.label :content %><br />     <%= post_form.text_area :content %>   </div>   <h2>Tags</h2>   <%= render :partial => 'tags/form',              :locals => {:form => post_form} %>   <div class="actions">     <%= post_form.submit %>   </div> <% end %> ✔ app/views/posts/_form.html.erb ROR Lab.
  • 12. <p id="notice"><%= notice %></p>   <p>   <b>Name:</b>   <%= @post.name %> </p>   <p> module PostsHelper   <b>Title:</b>   def join_tags(post)   <%= @post.title %>     post.tags.map { |t| t.name }.join(", ") </p>   end   end <p>   <b>Content:</b> ✔ app/helpers/posts_helper.rb   <%= @post.content %> </p>   <p> <p>   <b>Tags:</b>   <b>Tags:</b>   <%= @post.tags.map { |t| t.name }.join(", ") %>   <%= join_tags(@post) %> </p> </p>   <h2>Comments</h2> <%= render @post.comments %>   <h2>Add a comment:</h2> <%= render "comments/form" %>     <%= link_to 'Edit Post', edit_post_path(@post) %> | <%= link_to 'Back to Posts', posts_path %> | ✔ app/views/posts/show.html.erb ROR Lab.
  • 13. <p id="notice"><%= notice %></p>   <p>   <b>Name:</b>   <%= @post.name %> </p>   <p> module PostsHelper   <b>Title:</b>   def join_tags(post)   <%= @post.title %>     post.tags.map { |t| t.name }.join(", ") </p>   end   end <p>   <b>Content:</b> ✔ app/helpers/posts_helper.rb   <%= @post.content %> </p>   <p> <p>   <b>Tags:</b>   <b>Tags:</b>   <%= join_tags(@post) %>   <%= join_tags(@post) %> </p> </p>   <h2>Comments</h2> <%= render @post.comments %>   <h2>Add a comment:</h2> <%= render "comments/form" %>     <%= link_to 'Edit Post', edit_post_path(@post) %> | <%= link_to 'Back to Posts', posts_path %> | ✔ app/views/posts/show.html.erb ROR Lab.
  • 14. Live Demo Creating a project ~ 3rd model, Tag ROR Lab.
  • 16.   ROR Lab.

Editor's Notes

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n