Kelly
Kelly

Reputation: 649

Javascript tied to link_to is being executed on page load?

I have an index page that loads a bunch of records. Each record has a "favorite" icon. Clicking "favorite" sends a POST to the server and reloads the page.

I'm trying to use jQuery (ujs??) for the POST.

Controller action now looks like this:

      def favorite
        @record = Record.find(params[:id])
        @record.toggle_flag("favorite")
      end

The favorite icon is being rendered with a partial on the index view and is a link_to:

    <%= link_to(
      icon,
      path,
      method: :post,
      remote: true
    ) %>

The app/views/records/favorite.js.erb file looks like this:

    console.log("I am executing");
    $("[data-id='icon']").update("<%= j render 'icon', { icon: @record.favorite_icon, path: favorite_record_path } %>");

When I try and load index, I get an error stating that @record is nil. But why is the JS being executed when loading index? Also, the console log is getting fired right away when loading index. I want the JS to execute on clicking the favorite icon.

Upvotes: 2

Views: 184

Answers (1)

Nitin
Nitin

Reputation: 7366

Your code seems to me perfect and it should work without such errors. It seems like some other js code trigger link click event on page load. So try search for that as well.

favorite.js.erb will execute only on js request not on html request and page load is html request.

So try find js code that firing click event.

Upvotes: 1

Related Questions