SlideShare a Scribd company logo
Cart Creation
What we’ll cover Using Sessions Public, Private, and Protected Methods in Ruby Relationships between models Active Record Callbacks & Validation Adding a button to a page More Functional Testing
Generate a shopping cart rails generate scaffold cart No foreign keys present Only one of the tables has a foreign key Need to recover the cart with every request
Rails Sessions By default, session info stored in a browser session cookie (4k limit) Database or memcached also available Don’t store data that can easily be outdated Serialized ActiveRecordobjects Cryptographically signed but unencrypted Don’t store critical information solely in the session
Associate the cart with a session app/controllers/application_controller.rb private defcurrent_cart Cart.find(session[:cart_id]) rescue ActiveRecord::RecordNotFound   cart = Cart.create    session[:cart_id] = cart.id  cart 	end
Public, Private, & Protected Methods Different from Java & C# Public methods can be invoked by anyone  Private methods accessible by an object from a derived class Protected methods accessible by other objects & objects from derived classes Inheritance doesn’t determine method visibility Private & protected methods visible from subclasses
Storing items in the cart rails generate scaffold line_itemproduct_id:integercart_id:integer By convention, singular of table name appended with “_id” Need to establish relationship in both the database and the model Model declarations add ability to build and navigate the relationship
ActiveRecord relationships One to One has_one :contained belongs_to :container One to Many has_many :contained belongs_to :container Table with foreign keys has the ‘belongs_to’
Add Relationship Specifiers class Cart < ActiveRecord::Base has_many :line_items, :dependent => :destroy end class LineItem < ActiveRecord::Base belongs_to :product belongs_to :cart end class Product < ActiveRecord::Base has_many :line_items end
What if we destroy a cart? Line_items dependent on cart :dependent => :destroy indicates that line_items are destroyed along with the cart destroy involves ActiveRecord validation logic, delete only removes from the database
What if we destroy a product? Make sure it isn’t contained in a cart
ActiveRecord Callbacks & Validations Callbacks invoked before & after operations For example save, delete, create, validate Can view unformatted data in ‘before’ callbacks Dates & Currency Returning the actual value ‘false’ stops the operation Add a handler or define as a method
Add a button Won’t be creating a new controller or a new action Creating an item in the cart, so use line_item controller Looking at generated code in line_item_controller.rb, we’ll use the ‘Create’ action ‘Create’ action called using HTTP Post button_to‘button label’,  ‘URL Path’, ‘HTML options’ Add ‘_path’ to controller to get URL path (i.e. line_item_path) Pass in hash values to URL path as parameters id extracted from ActiveRecord objects passed in app/views/store/index.html.erb <%= button_to ‘Add to Cart’, line_items_path(:product_id => product) %>
Modify line_item create By default, create parameter is a serialized line_item object - params[:line_item] Create a line_item based on the product id and add it to the cart
Modify line_item create (cont.) app/controllers/line_items_controller.rb
Update the functional test test/functional/line_items_controller_test.rb assigns() accesses instance variables in the controller being tested
Try it out http://localhost:3000/ Cart scaffolding didn’t show any attributes of what was just added
Modify the view app/views/cart/show.html.erb <h2>Your Pragmatic Cart</h2> <ul>    <% for item in @cart.line_items %>        <li><%= item.product.title %></li>    <% end %> </ul>
Try it out (again) http://localhost:3000/ Cart now shows what is contained Need to show each item only once (next chapter)
Homework Change the view so that clicking on a book’s image will also add the product to the cart Add a new session variable to record how many times the user accessed the store controller’s index action Add the counter to the template and display it on top of the catalog page Reset the counter to zero when adding to the cart Change template to display counter when > 5

More Related Content

What's hot

idlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHubidlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHub
somberfan2012
 
idlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHubidlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHub
clammyhysteria698
 
idlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHubidlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHub
clammyhysteria698
 
idlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHubidlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHub
successfuloutdo12
 
idlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHubidlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHub
ludicrousexcerp10
 
idlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHubidlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHub
clammyhysteria698
 
idlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHubidlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHub
successfuloutdo12
 
idlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHubidlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHub
somberfan2012
 
idlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHubidlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHub
ludicrousexcerp10
 
idlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHubidlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHub
somberfan2012
 
idlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHubidlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHub
somberfan2012
 
Telling Stories With RSpec
Telling Stories With RSpecTelling Stories With RSpec
Telling Stories With RSpec
rahoulb
 
RSpec User Stories
RSpec User StoriesRSpec User Stories
RSpec User Stories
rahoulb
 
Behat: Beyond the Basics
Behat: Beyond the BasicsBehat: Beyond the Basics
Behat: Beyond the Basics
Jessica Mauerhan
 
Integrating consumers IoT devices into Business Workflow
Integrating consumers IoT devices into Business WorkflowIntegrating consumers IoT devices into Business Workflow
Integrating consumers IoT devices into Business Workflow
Yakov Fain
 
Sub ID Implementation
Sub ID ImplementationSub ID Implementation
Sub ID Implementation
Revcontent
 

What's hot (17)

idlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHubidlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHub
 
idlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHubidlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHub
 
idlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHubidlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHub
 
idlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHubidlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHub
 
idlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHubidlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHub
 
idlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHubidlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHub
 
idlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHubidlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHub
 
idlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHubidlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHub
 
idlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHubidlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHub
 
idlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHubidlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHub
 
idlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHubidlesign/django-sitecats · GitHub
idlesign/django-sitecats · GitHub
 
Telling Stories With RSpec
Telling Stories With RSpecTelling Stories With RSpec
Telling Stories With RSpec
 
RSpec User Stories
RSpec User StoriesRSpec User Stories
RSpec User Stories
 
Built in filters
Built in filtersBuilt in filters
Built in filters
 
Behat: Beyond the Basics
Behat: Beyond the BasicsBehat: Beyond the Basics
Behat: Beyond the Basics
 
Integrating consumers IoT devices into Business Workflow
Integrating consumers IoT devices into Business WorkflowIntegrating consumers IoT devices into Business Workflow
Integrating consumers IoT devices into Business Workflow
 
Sub ID Implementation
Sub ID ImplementationSub ID Implementation
Sub ID Implementation
 

Viewers also liked

Java lab1 manual
Java lab1 manualJava lab1 manual
Java lab1 manual
nahalomar
 
5 Components of Digital Marketing Operations
5 Components of Digital Marketing Operations5 Components of Digital Marketing Operations
5 Components of Digital Marketing Operations
McKinsey on Marketing & Sales
 
Introduction to Java Programming Language
Introduction to Java Programming LanguageIntroduction to Java Programming Language
Introduction to Java Programming Language
jaimefrozr
 
Java programming course for beginners
Java programming course for beginnersJava programming course for beginners
Java programming course for beginners
Eduonix Learning Solutions
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
Veerabadra Badra
 

Viewers also liked (6)

Lvp jcreator
Lvp jcreatorLvp jcreator
Lvp jcreator
 
Java lab1 manual
Java lab1 manualJava lab1 manual
Java lab1 manual
 
5 Components of Digital Marketing Operations
5 Components of Digital Marketing Operations5 Components of Digital Marketing Operations
5 Components of Digital Marketing Operations
 
Introduction to Java Programming Language
Introduction to Java Programming LanguageIntroduction to Java Programming Language
Introduction to Java Programming Language
 
Java programming course for beginners
Java programming course for beginnersJava programming course for beginners
Java programming course for beginners
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 

Similar to Cart creation-101217222728-phpapp01

Magento Indexes
Magento IndexesMagento Indexes
Magento Indexes
Ivan Chepurnyi
 
Ruby on rails
Ruby on rails Ruby on rails
Ruby on rails
Mohit Jain
 
OSDC 2009 Rails Turtorial
OSDC 2009 Rails TurtorialOSDC 2009 Rails Turtorial
OSDC 2009 Rails TurtorialYi-Ting Cheng
 
Shopify Partner Social
Shopify Partner SocialShopify Partner Social
Shopify Partner Social
The Working Party
 
E-Bazaar
E-BazaarE-Bazaar
E-Bazaar
ayanthi1
 
WooCommerce CRUD and Data Store by Akeda Bagus
WooCommerce CRUD and Data Store by Akeda BagusWooCommerce CRUD and Data Store by Akeda Bagus
WooCommerce CRUD and Data Store by Akeda Bagus
WordCamp Indonesia
 
APIs for catalogs
APIs for catalogsAPIs for catalogs
APIs for catalogs
X.commerce
 
Intro To Mvc Development In Php
Intro To Mvc Development In PhpIntro To Mvc Development In Php
Intro To Mvc Development In Phpfunkatron
 
Ride on the Fast Track of Web with Ruby on Rails- Part 2
Ride on the Fast Track of Web with Ruby on Rails- Part 2Ride on the Fast Track of Web with Ruby on Rails- Part 2
Ride on the Fast Track of Web with Ruby on Rails- Part 2
A.K.M. Ahsrafuzzaman
 
Staying railsy - while scaling complexity or Ruby on Rails in Enterprise Soft...
Staying railsy - while scaling complexity or Ruby on Rails in Enterprise Soft...Staying railsy - while scaling complexity or Ruby on Rails in Enterprise Soft...
Staying railsy - while scaling complexity or Ruby on Rails in Enterprise Soft...
Coupa Software
 
4 introduction-php-mvc-cakephp-m4-controllers-slides
4 introduction-php-mvc-cakephp-m4-controllers-slides4 introduction-php-mvc-cakephp-m4-controllers-slides
4 introduction-php-mvc-cakephp-m4-controllers-slidesMasterCode.vn
 
Introduce cucumber
Introduce cucumberIntroduce cucumber
Introduce cucumber
Bachue Zhou
 
Resource and view
Resource and viewResource and view
Resource and viewPapp Laszlo
 
Jarv.us Showcase — SenchaCon 2011
Jarv.us Showcase — SenchaCon 2011Jarv.us Showcase — SenchaCon 2011
Jarv.us Showcase — SenchaCon 2011Chris Alfano
 
Useful Rails Plugins
Useful Rails PluginsUseful Rails Plugins
Useful Rails Plugins
navjeet
 
Windows Store app using XAML and C#: Enterprise Product Development
Windows Store app using XAML and C#: Enterprise Product Development Windows Store app using XAML and C#: Enterprise Product Development
Windows Store app using XAML and C#: Enterprise Product Development Mahmoud Hamed Mahmoud
 
Intro Open Social and Dashboards
Intro Open Social and DashboardsIntro Open Social and Dashboards
Intro Open Social and Dashboards
Atlassian
 
Building a Pyramid: Symfony Testing Strategies
Building a Pyramid: Symfony Testing StrategiesBuilding a Pyramid: Symfony Testing Strategies
Building a Pyramid: Symfony Testing Strategies
CiaranMcNulty
 

Similar to Cart creation-101217222728-phpapp01 (20)

Catalog display
Catalog displayCatalog display
Catalog display
 
Magento Indexes
Magento IndexesMagento Indexes
Magento Indexes
 
Ruby on rails
Ruby on rails Ruby on rails
Ruby on rails
 
Lecture9
Lecture9Lecture9
Lecture9
 
OSDC 2009 Rails Turtorial
OSDC 2009 Rails TurtorialOSDC 2009 Rails Turtorial
OSDC 2009 Rails Turtorial
 
Shopify Partner Social
Shopify Partner SocialShopify Partner Social
Shopify Partner Social
 
E-Bazaar
E-BazaarE-Bazaar
E-Bazaar
 
WooCommerce CRUD and Data Store by Akeda Bagus
WooCommerce CRUD and Data Store by Akeda BagusWooCommerce CRUD and Data Store by Akeda Bagus
WooCommerce CRUD and Data Store by Akeda Bagus
 
APIs for catalogs
APIs for catalogsAPIs for catalogs
APIs for catalogs
 
Intro To Mvc Development In Php
Intro To Mvc Development In PhpIntro To Mvc Development In Php
Intro To Mvc Development In Php
 
Ride on the Fast Track of Web with Ruby on Rails- Part 2
Ride on the Fast Track of Web with Ruby on Rails- Part 2Ride on the Fast Track of Web with Ruby on Rails- Part 2
Ride on the Fast Track of Web with Ruby on Rails- Part 2
 
Staying railsy - while scaling complexity or Ruby on Rails in Enterprise Soft...
Staying railsy - while scaling complexity or Ruby on Rails in Enterprise Soft...Staying railsy - while scaling complexity or Ruby on Rails in Enterprise Soft...
Staying railsy - while scaling complexity or Ruby on Rails in Enterprise Soft...
 
4 introduction-php-mvc-cakephp-m4-controllers-slides
4 introduction-php-mvc-cakephp-m4-controllers-slides4 introduction-php-mvc-cakephp-m4-controllers-slides
4 introduction-php-mvc-cakephp-m4-controllers-slides
 
Introduce cucumber
Introduce cucumberIntroduce cucumber
Introduce cucumber
 
Resource and view
Resource and viewResource and view
Resource and view
 
Jarv.us Showcase — SenchaCon 2011
Jarv.us Showcase — SenchaCon 2011Jarv.us Showcase — SenchaCon 2011
Jarv.us Showcase — SenchaCon 2011
 
Useful Rails Plugins
Useful Rails PluginsUseful Rails Plugins
Useful Rails Plugins
 
Windows Store app using XAML and C#: Enterprise Product Development
Windows Store app using XAML and C#: Enterprise Product Development Windows Store app using XAML and C#: Enterprise Product Development
Windows Store app using XAML and C#: Enterprise Product Development
 
Intro Open Social and Dashboards
Intro Open Social and DashboardsIntro Open Social and Dashboards
Intro Open Social and Dashboards
 
Building a Pyramid: Symfony Testing Strategies
Building a Pyramid: Symfony Testing StrategiesBuilding a Pyramid: Symfony Testing Strategies
Building a Pyramid: Symfony Testing Strategies
 

More from Jason Noble

Intro to TDD and BDD
Intro to TDD and BDDIntro to TDD and BDD
Intro to TDD and BDD
Jason Noble
 
Davinci git brown_bag
Davinci git brown_bagDavinci git brown_bag
Davinci git brown_bagJason Noble
 
Rspec 101
Rspec 101Rspec 101
Rspec 101
Jason Noble
 
Intro to Rails Give Camp Atlanta
Intro to Rails Give Camp AtlantaIntro to Rails Give Camp Atlanta
Intro to Rails Give Camp Atlanta
Jason Noble
 
Google apps
Google appsGoogle apps
Google apps
Jason Noble
 
Smarter cart
Smarter cartSmarter cart
Smarter cart
Jason Noble
 
Validation unit testing
Validation unit testingValidation unit testing
Validation unit testingJason Noble
 
Creating the application
Creating the applicationCreating the application
Creating the application
Jason Noble
 
Capistrano
CapistranoCapistrano
Capistrano
Jason Noble
 
Atlanta Pm Git 101
Atlanta Pm Git 101Atlanta Pm Git 101
Atlanta Pm Git 101
Jason Noble
 
Git101
Git101Git101
Git101
Jason Noble
 
Git Atlrug
Git AtlrugGit Atlrug
Git Atlrug
Jason Noble
 
Git102
Git102Git102
Git102
Jason Noble
 

More from Jason Noble (14)

Intro to TDD and BDD
Intro to TDD and BDDIntro to TDD and BDD
Intro to TDD and BDD
 
Davinci git brown_bag
Davinci git brown_bagDavinci git brown_bag
Davinci git brown_bag
 
Rspec 101
Rspec 101Rspec 101
Rspec 101
 
Intro to Rails Give Camp Atlanta
Intro to Rails Give Camp AtlantaIntro to Rails Give Camp Atlanta
Intro to Rails Give Camp Atlanta
 
Google apps
Google appsGoogle apps
Google apps
 
Smarter cart
Smarter cartSmarter cart
Smarter cart
 
Validation unit testing
Validation unit testingValidation unit testing
Validation unit testing
 
Creating the application
Creating the applicationCreating the application
Creating the application
 
Capistrano
CapistranoCapistrano
Capistrano
 
Atlanta Pm Git 101
Atlanta Pm Git 101Atlanta Pm Git 101
Atlanta Pm Git 101
 
Regex Intro
Regex IntroRegex Intro
Regex Intro
 
Git101
Git101Git101
Git101
 
Git Atlrug
Git AtlrugGit Atlrug
Git Atlrug
 
Git102
Git102Git102
Git102
 

Cart creation-101217222728-phpapp01

  • 2. What we’ll cover Using Sessions Public, Private, and Protected Methods in Ruby Relationships between models Active Record Callbacks & Validation Adding a button to a page More Functional Testing
  • 3. Generate a shopping cart rails generate scaffold cart No foreign keys present Only one of the tables has a foreign key Need to recover the cart with every request
  • 4. Rails Sessions By default, session info stored in a browser session cookie (4k limit) Database or memcached also available Don’t store data that can easily be outdated Serialized ActiveRecordobjects Cryptographically signed but unencrypted Don’t store critical information solely in the session
  • 5. Associate the cart with a session app/controllers/application_controller.rb private defcurrent_cart Cart.find(session[:cart_id]) rescue ActiveRecord::RecordNotFound cart = Cart.create session[:cart_id] = cart.id cart end
  • 6. Public, Private, & Protected Methods Different from Java & C# Public methods can be invoked by anyone Private methods accessible by an object from a derived class Protected methods accessible by other objects & objects from derived classes Inheritance doesn’t determine method visibility Private & protected methods visible from subclasses
  • 7. Storing items in the cart rails generate scaffold line_itemproduct_id:integercart_id:integer By convention, singular of table name appended with “_id” Need to establish relationship in both the database and the model Model declarations add ability to build and navigate the relationship
  • 8. ActiveRecord relationships One to One has_one :contained belongs_to :container One to Many has_many :contained belongs_to :container Table with foreign keys has the ‘belongs_to’
  • 9. Add Relationship Specifiers class Cart < ActiveRecord::Base has_many :line_items, :dependent => :destroy end class LineItem < ActiveRecord::Base belongs_to :product belongs_to :cart end class Product < ActiveRecord::Base has_many :line_items end
  • 10. What if we destroy a cart? Line_items dependent on cart :dependent => :destroy indicates that line_items are destroyed along with the cart destroy involves ActiveRecord validation logic, delete only removes from the database
  • 11. What if we destroy a product? Make sure it isn’t contained in a cart
  • 12. ActiveRecord Callbacks & Validations Callbacks invoked before & after operations For example save, delete, create, validate Can view unformatted data in ‘before’ callbacks Dates & Currency Returning the actual value ‘false’ stops the operation Add a handler or define as a method
  • 13. Add a button Won’t be creating a new controller or a new action Creating an item in the cart, so use line_item controller Looking at generated code in line_item_controller.rb, we’ll use the ‘Create’ action ‘Create’ action called using HTTP Post button_to‘button label’, ‘URL Path’, ‘HTML options’ Add ‘_path’ to controller to get URL path (i.e. line_item_path) Pass in hash values to URL path as parameters id extracted from ActiveRecord objects passed in app/views/store/index.html.erb <%= button_to ‘Add to Cart’, line_items_path(:product_id => product) %>
  • 14. Modify line_item create By default, create parameter is a serialized line_item object - params[:line_item] Create a line_item based on the product id and add it to the cart
  • 15. Modify line_item create (cont.) app/controllers/line_items_controller.rb
  • 16. Update the functional test test/functional/line_items_controller_test.rb assigns() accesses instance variables in the controller being tested
  • 17. Try it out http://localhost:3000/ Cart scaffolding didn’t show any attributes of what was just added
  • 18. Modify the view app/views/cart/show.html.erb <h2>Your Pragmatic Cart</h2> <ul> <% for item in @cart.line_items %> <li><%= item.product.title %></li> <% end %> </ul>
  • 19. Try it out (again) http://localhost:3000/ Cart now shows what is contained Need to show each item only once (next chapter)
  • 20. Homework Change the view so that clicking on a book’s image will also add the product to the cart Add a new session variable to record how many times the user accessed the store controller’s index action Add the counter to the template and display it on top of the catalog page Reset the counter to zero when adding to the cart Change template to display counter when > 5

Editor's Notes

  1. - current_cart available to all controllers‘create’ an ActiveRecord method that creates &amp; stores in the databaseas an aside, ‘private’ will look wrong to those from a Java or C# background
  2. Other relationships are available - Many to Many - Relationships through a 3rd model
  3. Can do things like li = LineItem.find(…) puts “This is for #{li.product.title}”Cart can reference its collection cart.line_items.count
  4. Use an ActiveRecord callback to perform validation
  5. - Unformatted data in validation callback
  6. Links use HTTP GET, Buttons use HTTP POSTbutton_to uses &lt;form&gt; and &lt;div&gt; elements which drop down to another line unless made inline with CSS
  7. ActiveRecord ‘build’ allows you to add an object to the collection with references set
  8. - Updatetest to reflect changes in the controller- In the “real world”, we would update the test first- rake test:functionals