Home > Blockchain >  Ruby on Rails 7 - js.erb file not running
Ruby on Rails 7 - js.erb file not running

Time:12-31

I'm currently having an issue of my "like.js.erb" file not running. I can see that the GET request is successful and the response is the code, but the js.erb code is not running. I put a simple "console.log("hello")" which is not running either. Any help would be greatly appreciated

/controllers/likes_controller.rb

class LikesController < ApplicationController
    before_action :authenticate_account!
    protect_from_forgery except: :save_like
    
    def save_like
        @like = Like.new(post_id: params[:post_id], account_id: current_account.id)
        @post_id = params[:post_id]

        respond_to do |format|
            format.js{
                if @like.save
                    @success = true
                else
                    @success = false
                end

                render "posts/like"
            }
        end
    end
end

likes_controller.js

import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
  connect() {
    this.element.addEventListener("click", function(e){
        var post_id = e.target.getAttribute("data-id")
        console.log(post_id)
       
        var oReq = new XMLHttpRequest();
        oReq.open("GET", "/post/like/"   post_id)
        oReq.send()
    })
  }
}

/views/posts/like.js.erb

console.log("hello")

CodePudding user response:

I ran into this issue as well on my upgrade.

My fix was changing the form declaration from:

<%= form_with url: sign_in_path do |f| %>

to

<%= form_with url: sign_in_path, local: false do |f| %>

Setting 'local: false' sets the form request in as 'JS'.

CodePudding user response:

If anyone else is struggling with this situation, from what I read js.erb files have been depreciated in Rails 7 due to security concerns. Rails 7 also uses import_maps rather than webpack so all javascript files should be ran from app/javascript/controllers. I ended up just removing my js.erb file and moving its contents to my javascript/controllers and it's working fine now.

https://www.youtube.com/watch?v=PtxZvFnL2i0&ab_channel=DavidHeinemeierHansson

This video helped me understand how to run javascript in Ruby On Rails 7 Applications.

  • Related