Link after_create_commit to a "product_id" instead of "products"


I’m trying to integrate hotwire into a production app. Yet, I do not fully understand how to approach the following situation (see screenshot as visual helper below).

Use case: supermarket application.
A shop lists all the different products on it’s show page as cards with a picture, description, and price. Each product has a green button (Toevoegen) that will add the product to the cart. The green button triggers the creation of a line_item (line_items_controller#create) that connects the cart and the product. After adding an item to a cart, the green button will be replaced by a form that includes a minus and plus button to increment the quantity.

How can the after_create_commit of the line_item model append the information to a specific product_id instead of the plural line_items or products? I’ve tried to use broadcasts_to :product yet without success.

class LineItem
 after_create_commit { broadcast_prepend_to "XXXXX" }

This stackoverflow user seems to face a similar challenge.

I’d very much appreciate it if someone could elaborate on how to best tackle this or point me in the right direction.

Thank you.

broadcasts_prepend_to can take a target option, which is the DOM id you want to prepend to. You can also pass through an Active Record and get that converted into a dom id, a la the dom_id helper. So you’d do something like: broadcasts_prepend_to "XXX", target: product. Does that work?

That was the missing piece, how to set a custom target!

Just ralized that it’s not even needed to broadcast the add to cart upon creation of a line_item. A turbo_stream from the controller works just fine!

render turbo_stream: turbo_stream.replace("counter_#{}",
                                                    partial: 'line_items/line_item',
                                                    locals: { line_item: @line_item })

Thanks for your help @dan.

1 Like