RomanTurner

RomanTurner

Journal: Agile Web Development with Rails 6

Agile Web Development with Rails 6 Chapter 11. Task F


Currently reading and working through AWDR6 by Sam Ruby, David Bryant Copeland, and Dave Thomas. I have run into a couple issues and worked through them. I couldn’t find some solutions so decided to make a work log here for anyone else that might be working through this book.

The Pragmatic Programmers are amazing enough to have hosted this book on Medium as well. If you are interested in following along, or practicing yourself follow the link .


Chapter 11. Task F: Add a Dash of Ajax

Summary

  • Moved the shopping cart into the sidebar. We then arranged for the create action to re-display the catalog page.
  • We used remote:true to invoke the LineItemsController.create() action using AJAX
  • We used an ERB template to create JavaScript that’ll execute on the the client
  • We wrote a helper method that renders the cart only if it has anything in it
  • We used Action Cable and JavaScript to update the catalog display whenever a product changes

Issue: ArgumentError in ProductsController#update “wrong number of arguments (given 1, expected 2)”

Investigation: ‘Maybe it’s expecting an actual argument, not a keyword arg in the second place? The code you wrote passes (with a warning) on Ruby 2.7 but no longer works on Ruby 3.’ — https://stackoverflow.com/a/68432507

Solution: Wrap the argument in a hash, like it expects now (Running Ruby -v 3+). The p_id key is to help in the play time answer below.

  • We wrote a test that verifies not only the creation of a line item but also the content of the response that’s returned from such a request.

Playtime

Issue: This problem has starts a cascade of issues. Mainly because I am used to working on JavaScript frameworks, little quirks that I am not used to pop up and I don’t know how to solve them within this paradigm. For instance, how do I change the flash[:notice] with ajax? Once you dip your toes into the ajax you start conflating the your controllers with so many response formats and such. Wish there was an easier way.

Current Solution: If you have a methodology to follow dealing with this, please share. But for now my solution had to be two-fold: Because the cart can be emptied by the ‘empty cart button’ or by removing line items. Both solutions are the same and seem hacky to me.

\\ line_items/destroy.js.erb
cart = document.getElementById("cart")
cart.innerHTML = "<%= j render_if @cart && @cart.line_items.any?, @cart %>"
------------------------------------------------------------------//carts/destroy.js.erb
cart = document.getElementById("cart")
cart.hidden = true;

Problem created by the solution: The cart now has a hidden property. If we want to add an item it will, but the cart will not be visible.

Solution to problem created by solution: Make sure it isn’t hidden.

\\ line_items/create.js.erb
cart = document.getElementById("cart")
cart.hidden = false; <--------
cart.innerHTML = "<%= j render(@cart) %>"

[✓]- Add a button next to each item in the cart. When clicked, it should invoke an action to decrement the quantity of the item, deleting it from the cart when the quantity reaches zero.

Did this in an earlier chapter. With the same conditional qualifier, just saw into the future. Task E Cart view with buttons below.

[✓]- Get it working without Ajax, and then add it afterwards.

Issue: “ArgumentError (too few arguments): in Format, in Edit”

Investigation: Responding with multiple formats. Imagine having your js turned off, you still would want your requests to work.

Solution:

line_item #edit format.js example

Checkout the repo for full the controller. Before action set_cart is crucial for redrawing the cart with Ajax.


[✓]- Make images clickable. In response to a click, add the associated product to the cart.

Issue: This presented a challenge to me because I learned Rails as an API, so pivotting my mindset from inline vanilla JS or JSX in React to UJS (Unobtrusive JavaScript) methodology in Rails.

Investigation: I spent waaay too much time trying to figure out how to put an onclick event on an image or use the link_to and image_tag helper until I read and inspected the HTML.

I wanted to mimic the button_to and action that the ‘Add to Cart’ button had.
With further inspection I saw that Rails helper button_to creates a form with an submit input. This spurred my thinking that we could do the same thing with the image.

Activating hyperlinks always results in an HTTP GET request. However, if your application is RESTful, some links are in fact actions that change data on the server, and must be performed with non-GET requests. This attribute allows marking up such links with an explicit method such as “post”, “put” or “delete”.
The way it works is that, when the link is activated, it constructs a hidden form in the document with the “action” attribute corresponding to “href” value of the link, and the method corresponding to data-method value, and submits that form. — https://guides.rubyonrails.org/working_with_javascript_in_rails.html#an-introduction-to-ajax

Solution: I found a helper called image_submit_tag, which creates a submit input with they type=‘image’. Surrounded that with a form with remote data (or in this case local:false) and it worked! It created the same action as the button. The cart scss also reacted appropriately by animating the background.

Issue cont.: With this now working as the image it broke my scss for my image for the store presentation.

Solution: It is no longer an img tag, so of course it wouldn’t work. It is now a input[type=’image’], just change that out and it is Gucci.


[✓]- When a product changes, highlight the product that changed in response to receiving a broadcast message.

Issue: I am not too familiar with UJS methodology.

Investigation: This works like a pub/sub so I tried tooling around with it to make it work. The biggest issue here was placement. I was brain tired and kept adding the class to the list before I would then overwrite the innerHTML of the body 😩 Lame move on my part. But I finally got it to go by moving it down.

Solution:

Borrowed the cart highlight class, because why not.


Photo by Susan Q Yin on Unsplash

I am participating in a Ruby book club and if you are interested in joining please direct message me. Would love to meet you and get better together.

By Roman Turner on October 7, 2021.

Canonical link

Exported from Medium on October 12, 2021.

Where Next?

Popular Community topics Top

finner
As one of my New Year resolutions is to read more tech I’ve decided on an attempt to document my travels in Mannings Modern Java in Actio...
New
mafinar
Crystal recently reached version 1. I had been following it for awhile but never got to really learn it. Most languages I picked up out o...
New
rustkas
To be a more productive reader when rereading a book, it is very convenient to create small rebar3 projects based on books’ samples and i...
New
TwistingTwists
I have read first chapter. Will add my notes / code tries / self exploration as I go along! Thank you @AstonJ for encouraging to start ...
New
ohm
I would love to begin a book club with Mike Amundsen’s (@mamund) book Design and Build Great Web APIs. It seems that building new syste...
New
TwistingTwists
This is my Journal for readings on Designing Elixir Systems with OTP. Will post chapter 01 tomorrow! Stay tuned!
New
AstonJ
With Tailwind now the default CSS framework shipped with Phoenix we thought it would be nice to run this book club on the Elixir Forum. ...
New
AstonJ
With AI set to play a big role in our industry Elixir users are lucky to have Nx, so we’re running our Nx related book club on Genetic Al...
New
AstonJ
With Phoenix and LiveView having recently had a fairly major release, and Programming Phoenix LiveView being updated too, we thought it w...
New
alvinkatojr
https://fs.blog/mental-models/ I’ve been reading Farnham Street for a while, and this topic is the recommended starting point for new re...
New

Other popular topics Top

Devtalk
Reading something? Working on something? Planning something? Changing jobs even!? If you’re up for sharing, please let us know what you’...
1031 17377 381
New
ohm
Which, if any, games do you play? On what platform? I just bought (and completed) Minecraft Dungeons for my Nintendo Switch. Other than ...
New
siddhant3030
I’m thinking of buying a monitor that I can rotate to use as a vertical monitor? Also, I want to know if someone is using it for program...
New
dimitarvp
Small essay with thoughts on macOS vs. Linux: I know @Exadra37 is just waiting around the corner to scream at me “I TOLD YOU SO!!!” but I...
New
AstonJ
If you are experiencing Rails console using 100% CPU on your dev machine, then updating your development and test gems might fix the issu...
New
AstonJ
We’ve talked about his book briefly here but it is quickly becoming obsolete - so he’s decided to create a series of 7 podcasts, the firs...
New
PragmaticBookshelf
Author Spotlight Rebecca Skinner @RebeccaSkinner Welcome to our latest author spotlight, where we sit down with Rebecca Skinner, auth...
New
AstonJ
If you want a quick and easy way to block any website on your Mac using Little Snitch simply… File &gt; New Rule: And select Deny, O...
New
First poster: bot
zig/http.zig at 7cf2cbb33ef34c1d211135f56d30fe23b6cacd42 · ziglang/zig. General-purpose programming language and toolchain for maintaini...
New
AstonJ
This is a very quick guide, you just need to: Download LM Studio: https://lmstudio.ai/ Click on search Type DeepSeek, then select the o...
New

Latest in Agile Web Development with Rails 6

Agile Web Development with Rails 6 Portal