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 (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 2
RORLAB
 
Action View Form Helpers - 2, Season 2
Action View Form Helpers - 2, Season 2Action View Form Helpers - 2, Season 2
Action View Form Helpers - 2, Season 2
RORLAB
 
OSDC 2009 Rails Turtorial
OSDC 2009 Rails TurtorialOSDC 2009 Rails Turtorial
OSDC 2009 Rails Turtorial
Yi-Ting Cheng
 
Your Custom WordPress Admin Pages Suck
Your Custom WordPress Admin Pages SuckYour Custom WordPress Admin Pages Suck
Your Custom WordPress Admin Pages Suck
Anthony Montalbano
 
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
 
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
 
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
 

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

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 2
RORLAB
 
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
RORLAB
 
ActiveRecord Query Interface (2), Season 2
ActiveRecord Query Interface (2), Season 2ActiveRecord Query Interface (2), Season 2
ActiveRecord Query Interface (2), Season 2
RORLAB
 
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
RORLAB
 

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

Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
AnaAcapella
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
KarakKing
 
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
QucHHunhnh
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
ZurliaSoop
 

Recently uploaded (20)

Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
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
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
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
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 

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