title: In Rails, how would you create a DB entry asynchronously using fetch?
body: <p><strong>What I want to achieve</strong></p>
  <p>When the user clicks on the thumbs up, in the database join table <code>likes(user_id, project_id)</code>, an entry is created to reflect the users upvote on the project. The count is updated unless the user has already upvoted the project before.</p>
  <p>I was hoping a simple JS fetch request would do. Unfortunately, it results in a 500 error.</p>
  <p><code>home.html.erb</code></p>
  <pre class="lang-html prettyprint-override"><code>&lt;div class=&quot;card&quot; data-project-id='1'&gt;
  ...
     &lt;span class=&quot;tag upvotes&quot;&gt; 143&lt;/span&gt;
  ...
  &lt;/div&gt;
  </code></pre>
  <p><code>application.js</code></p>
  <pre class="lang-js prettyprint-override"><code>...
  document.addEventListener('turbolinks:load', () =&gt; {
  ...
  
    const upvote = () =&gt; {
      document.querySelectorAll('.tag.upvotes').forEach((tag) =&gt; {
        tag.addEventListener('click', (e) =&gt; {
          const project_id = e.target.closest('.card').dataset.projectId;
          fetch(`projects/${project_id}/like/`, {
            method: 'post'
          })
          .then(response =&gt; response.json())
          .then(data =&gt; {
            console.log('Success:', data);
          })
          .catch((error) =&gt; {
            console.error('Error:', error);
          });
        });
      });
    }
  
    upvote();
  
  });
  </code></pre>
  <p><code>routes.rb</code></p>
  <pre class="lang-rb prettyprint-override"><code>Rails.application.routes.draw do
    ...
    post 'projects/:id/like', to: 'projects#like'
  end
  </code></pre>
  <p><code>projects_controller.rb</code></p>
  <pre class="lang-rb prettyprint-override"><code>class ProjectsController &lt; ApplicationController
    ...
  
    def like
      @project = Project.find(params[:id])
      @like = Like.create(user: current_user, project: @project) unless Like.where(user: current_user, project: @project)
      render json: Like.where(project: @project).count.to_json
    end
  end
  </code></pre>