ruby-on-railsturbolinksstimulusjsturbostimulus-rails

How execute js code in rails 7 'create.turbo_stream.erb' file


here is my comment controller code

    def create
     @comment = current_user.comments.new(comment_params)
     @feed = Feed.find(params[:comment][:feed_id])
     @comment.commentable = @feed
     @parent = params[:comment][:parent] if params[:comment][:parent].present?
     respond_to do |format|
     if @comment.save
      format.turbo_stream
      format.html { redirect_to feeds_path, notice: "Comment was successfully created." }
      format.json { render :show, status: :created, location: @comment }
     else
      format.html { render :new, status: :unprocessable_entity }
      format.json { render json: @comment.errors, status: :unprocessable_entity }
     end
    end
   end

my 'create.turbo_stream.erb' code is below

  <%if @parent.present?%>
     <%= turbo_stream.update("feeds-list-parent-#{@parent}",
          partial: "feeds/feed",
          locals: { feed: @feed }) %>
  <%else%>
      <%= turbo_stream.update("feeds-list-#{@feed.id}",
          partial: "feeds/feed",
          locals: { feed: @feed }) %>
  <%end%>
  console.log('hi') # this is not working here and no log. also <script> tag is not working.

How this is possible to execute some js code, beacause i want to hide pop up div using js here?

i tried different option to execute js but not working.


Solution

  • <script> tag has to be inside the turbo stream to be executable:

    <%= turbo_stream.update "feeds-list-#{@feed.id}" do %>
      <%= render "feeds/feed", feed: @feed %>
      <script>
        console.log("hi")
      </script>
    <% end %>
    

    or in a separate turbo stream:

    <%= turbo_stream.update "feeds-list-#{@feed.id}", partial: "feeds/feed", locals: {feed: @feed} %>
    
    <%= turbo_stream.after "feeds-list-#{@feed.id}" do %>
      <script>
        console.log("hi")
      </script>
    <% end %>