Ask A Question

Notifications

You’re not receiving notifications from this thread.

Turbo stream problem

Anders asked in Rails

Hello...

I'm having a problem with a view not fully auto-updating using turbo.
It currently only works when updating or destroying.

So to keep it kinda short, I have a site where users can crud some products. On an office screen, products are listed. All updates shows up automatically. Newly created products can only be loaded if this view is refreshed.

The product.rb simply uses

broadcasts

The route has

resources :products
get "screen", to: "products#screen"

The new and edit templates doesn't use turbo. And the product_controller simply does something like:

def create
        @product = Product.new(product_params)
        if @product.save
            redirect_to products_path
        else
            render :new
        end
 end

In the products_controller I also define the 'screen'

def screen
        @products = Product.all
end

And on the views/products/screen.html.erb I do

<% @products.each do |product| %>
  <%= turbo_stream_from product %>
  <%= render partial: "product", locals: { product: product } %>
<% end %>

and the views/products/_product.html.erb

<div id="<%= dom_id product%>">
  <%= product_name %>
</div>

What am I missing?
Thank you

Reply

You may need to add a broadcast_to statement in your create action in the product controller like this:

def create
  @product = Product.new(product_params)
  if @product.save
    ActionCable.server.broadcast_to('products', product: @product)
    redirect_to products_path
  else
    render :new
  end
end

This broadcast_to statement will send out a signal to the 'products' channel with the newly created product. With this signal, the view will be updated automatically with the newly created product without needing to refresh the page.

Reply

Thank you for your reply...

I was under the impression that

broadcasts

would be enough. But that doesn't include create I guess.

ActionCable seems like a hassle to set up. Thought turbo could do this.
I'll just add some javascript 🫣 to handle some kind of fetch new function

Reply

So did you solve your problem?

Reply

I wanna know the method

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 86,946+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.