SlideShare uma empresa Scribd logo
1 de 20
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

Mais conteúdo relacionado

Último

The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????blackmambaettijean
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 

Último (20)

The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 

Destaque

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by HubspotMarius Sescu
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTExpeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 

Destaque (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

Agile Web Dev. With Rails Ch 7 - Cart Creation

  • 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

Notas do Editor

  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