How to retrieve all user_notes in Rails 6 using Bootstrap 5 and Ajax Calls, instead of only fetching the notes belonging to the current

I'm struggling with a issue related to my joined table called user_notes, which connects an adventure_id with a user_id (belongs_to) and includes a longtext field called :note. The problem I'm facing is that all users can see each other's notes on the page when they should be private. Despite trying different queries in the controller and conditionals in the JS, the issue persists. Although the ajax calls and modal/form updates are functioning correctly, any attempt to display only the current_user's notes breaks the ajax functionality.

In the user_notes_controller.rb:

  def index
    @adventure = Adventure.find(params[:adventure_id])
    @user = current_user
    @user_notes = current_user.user_notes.where(adventure: @adventure).order(created_at: :desc)
  end

Within index.html.erb:

<div class="container">

  <div class="row mt-4 card">
    <div class="col-12">
      <h3 class="text-center">Add a New Note</h3>
      <h6 class="text-center">(SHIFT + RETURN/ENTER for a new line)</h6>

      <%= form_with(model: [@adventure, UserNote.new], url: adventure_user_notes_path(@adventure), local: false, method: :post, id: 'note_form') do |form| %>
        <%= form.text_area :note, oninput: 'this.style.height = "";this.style.height = this.scrollHeight + "px"', class: "form-control", placeholder: 'Add a new note...' %>
        <%= form.hidden_field :adventure_id, value: @adventure.id %>
        <%= form.hidden_field :user_id, value: @user.id %>
    </div>
      <div class="d-inline-flex justify-content-center">
        <%= form.submit 'Save Note', class: "btn btn-outline-success text-end" %>
      </div>
  </div>

      <% end %>


      <!-- Display Saved Notes -->
      <div class="container-fluid overflow-auto">
        <div id="user-notes-list">
          <%= render partial: 'user_notes/note', collection: @adventure.user_notes.order(created_at: :desc), as: :note, locals: { adventure_id: @adventure.id, user_id: @user.id } %>
        </div>
      </div>
      
</div><!-- End Container -->

<!-- JavaScript logic goes here -->
<script> ... </script>

To manage the issue of displaying incorrect notes, I added

data-current-user-id="<%= current_user.id %>"
to the body tag in application.html.erb. However, despite various attempts, including wrapping the _note.html.erb code with
<% if note.user_id == @user.id %>
, no viable solution has been found yet after working on it for several hours. Any suggestions or solutions would be greatly appreciated.

Answer №1

Issue resolved. Solution for individuals facing similar challenges:

In index.html.erb when rendering a partial

<%= render partial: 'user_comments/comment', collection: @user_comments, as: :comment %>

eliminating unnecessary local variables. In the _comments partial, updated data-adventure-id's value to

<%= comment.adventure_id %>
. Ensured that
@user_comments = current_user.user_comments.where(adventure: @adventure).order(created_at: :desc)
was included in every controller action (index, create, update, destroy). Attempted to streamline the code in the controller by setting it as a before_action, but it caused issues (didn't show previous user's comments), so I opted against following the DRY principle and restored it, resulting in a well-functioning system. Hopefully, this guidance proves useful for others navigating AJAX/JS integration with a connected table.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Shadows are mysteriously absent in the 3D scene despite having the castShadow and receiveShadow properties enabled

View image description here Hello, I'm facing an issue with the shadows in my 3D model. Even though I have enabled shadow casting and receiving in the code, the shadow is not appearing on my model. You can reference the provided image or visit this ...

Is it recommended to utilize the jQuery Ajax API within jQueryMobile?

Currently, I am in the process of developing a Mobile web application using HTML5, CSS3, JavaScript, and jQueryMobile. I will then encapsulate it with Phonegap. As someone who is new to web development, I find myself pondering whether when utilizing jQuer ...

Using JavaScript to utilize a variable containing a .match method with Regex Expression

Recently, I started delving into the world of regex with the aim of incorporating variables in my matches. Imagine I have a string that reads "Total: $168" My goal is to extract just the numerical value; 168. This is what I currently have: totalCost = t ...

Activate the Select List to Appear Only When a Search is Conducted

Currently, I have implemented the react-select API in order to provide language options for selection. <Select isMulti name="langs" options={langOptions} defaultValue={{ value: "English", label: "English", nativeNam ...

Accepting parameters in an Express POST requestWondering how to accept parameters in

Currently, I have an API that requires passing car make, model, and year in the URL. Using an express router post call, I am able to retrieve the query parameters and set them to an object. I need to ensure that the URL can accept parameters like this: lo ...

Guide on incorporating an HTML element within a binding in Nuxt or Vue

I'm struggling with adding an HTML element <br /> inside a data bind. I want to modify the text "I like playing games" to include a line break, making it read as "I like playing <br /> games", but I can't seem to get it right within t ...

Avoid the headache of accidentally submitting a form multiple times with the help of rails 4 remote: true

view = form_tag foo_path, method: :get, class: 'form-inline', role: 'form', remote: true do .form-group = select_tag :year, options_for_select(@years, Date.today.year), class: 'form-control', prompt: 'Year' ...

Mastering the Art of jQuery: Easily Choosing and Concealing a Div Element

I'm currently facing challenges in removing a div upon successful AJAX completion. The issue I'm encountering is that the word "Added" appears twice after success, indicating that I am not properly selecting the two divs containing it. Any sugges ...

Node replication including a drop-down menu

Is there a way to clone a dropdown menu and text box with their values, then append them to the next line when clicking a button? Check out my HTML code snippet: <div class="container"> <div class="mynode"> <span class=& ...

I am in need of a datepicker for my project that will display the END date as the current date and set the START date as 7 days before the END date

$(document).ready(function () { $("#end").datepicker({ dateFormat: "dd-M-yy", minDate: 0, onSelect: function () { var start = $('#start'); var startDate = $(this).datepicker('getDate') ...

I'm having trouble with my form submission using AJAX, as it's not echoing

I am currently testing the submission of a form using Ajax (submitting to my own page "new1.php"). What I am aiming for is to have the first and last name echoed after clicking the submit button. However, I am not seeing the first and last name displayed ...

Navigating the right URL using Aurelia in conjunction with .Net Core and an IIS web application

Running my Aurelia app under Asp MVC Core 1.0 presents a challenge when deploying to IIS. The app uses HttpClient to interact with controller actions that return JSON data. All the actions are in the Home controller, and the HttpClient is configured like t ...

What methods are most effective for evaluating the properties you send to offspring elements?

Currently, I'm in the process of testing a component using Vue test utils and Jest. I'm curious about the most effective method to verify that the correct values are being passed to child components through their props. Specifically, I want to e ...

Encountering a display issue within a port using Express

Recently, I enrolled in an advanced ExpressJS course. While exploring the course website, I stumbled upon the "hello world" section. Intrigued, I decided to copy and paste the code provided below: const express = require('express') const app = ex ...

Issue with ng-model in ng-repeat not functional

I need assistance with setting the ng-model for answer option checkboxes in a list of questions and options. I am currently using two ng-repeat directives to display the questions and options, but I'm unsure how to set the ng-model to capture all sele ...

Is there a way to incorporate AJAX queuing in react-native through the use of fetch?

Recently, I successfully integrated AJAX calls into my react-native project using fetch. However, I've encountered some difficulties in implementing proper queuing for these calls. Can anyone offer some assistance or guidance on this issue? ...

Utilize Jquery to dynamically replace HTML partials based on the device's screen resolution

Currently working on a project using Bootstrap 3, the client has requested significant changes to the structure for mobile views. In previous projects, I have utilized Zurb Foundations Interchange: - and found it to be fantastic! I am curious if there a ...

Struggling to locate a route for the React styled components image

I'm having trouble locating the correct path for the image in my React styled components. I believe the path is correct, but could the issue be related to styled-components? Check it out here import styled from "styled-components"; export defaul ...

One way to display a div's inner HTML as its background is to apply a CSS rule

Help needed! <div class="container">red</div> <div class="container">green</div> <div class="container">#eeeeee</div> I am trying to dynamically set background colors for multiple divs based on their inner HTML co ...

Steps for resetting all Bootstrap JS controls:

On my Bootstrap website, I am dynamically loading HTML content using an AJAX jQuery script. The loaded content contains Bootstrap JavaScript controls such as dropdowns, tabs, and collapse elements. However, since these are loaded after the DOM event, none ...