AJAX Object Creation: Only Visible After Manual Refresh

Currently, I am in the process of building a basic to-do app that includes multiple different lists, each of which contains a variety of items. My main objective is to integrate AJAX functionality into the creation and display of lists on the lists#index page. Even though new lists are successfully created, they do not appear until the page is manually refreshed. Here's an excerpt from the server log outlining the issue:

 List Exists (0.1ms)  SELECT  1 AS one FROM "lists" WHERE ("lists"."id" IS NOT NULL) AND "lists"."slug" = ? LIMIT 1  [["slug", "new-list-again"]]
  SQL (0.3ms)  INSERT INTO "lists" ("name", "shared_with", "user_id", "slug") VALUES (?, ?, ?, ?)  [["name", "New List Again"], ["shared_with", ""], ["user_id", 2], ["slug", "new-list-again-dc08b63c-1d57-42ea-a725-a2c5c185e529"]]
   (0.7ms)  commit transaction
  Rendered lists/create.js.erb (7.9ms)
Completed 500 Internal Server Error in 22ms (ActiveRecord: 1.4ms)

NoMethodError - undefined method `valid?' for nil:NilClass:
  app/views/lists/create.js.erb:1:in `_app_views_lists_create_js_erb___822718317456566494_70187652289300'

The following code snippet is relevant to my lists#index page:

<h1>My Lists (<%= @lists.count %>)</h1>
<% if @lists.count == 0 %>
  <p>You don't have any lists yet! Why don't we remedy that?<p>
<% end %>

<div class='list-form'>
  <%= render partial: 'lists/form', locals: { list: @list } %>
</div>

<div class="js-lists">
  <%= render @lists %>
</div>

This next code block shows my lists/_form partial:

<div class="row">
  <div class="col-xs-12">
    <%= form_for @list, format: :js, remote: true do |f| %>
      <div class="form-group col-sm-6">
        <%= f.label :name %>
        <%= f.text_field :name, class: 'form-control', placeholder: "Enter List Name" %>
      </div>

      <div class="form-group col-sm-6">
        <%= f.label 'Share My List (Not Required)' %>
        <%= f.text_field :shared_with, class: 'form-control', placeholder: "Enter Emails Separated by Commas" %>
      </div>

      <div class="text-center"><%= f.submit "Let's Go!", class: 'btn btn-primary' %></div>
    <% end %>
  </div>
</div>

Here is the lists/_list partial:

<%= link_to list_path(list) do %>
  <h4><%= list.name %>
    <% if list.shared_with != "" %>
     (Shared)
    <% end %>
  <% end %>
 <small>( <%= list.items.count %> Items, <%= link_to "Edit", edit_list_path(list) %> | <%= link_to "Delete", list_path(list), method: :delete %> )</small></h4>

Additionally, here is my create.js.erb file:

<% if @item.valid? %>
  $('.js-lists').prepend("<%= escape_javascript(render partial: 'lists/list', locals: { list: @list }) %>");
  $('.list-form').html("<%= escape_javascript(render partial: 'lists/form', locals: { list: @new_list }) %>");
<% else %>
  $('.flash').prepend("<div class='alert alert-danger'><button type='button' class='close' data-dismiss='alert'>&times;</button><%= flash.now[:alert] %></div>");
  $('.new-list').html("<%= escape_javascript(render partial: 'lists/form', locals: { list: @list }) %>");
<% end %>

Lastly, here is the create method within my lists_controller:

def create
    @list = List.new(list_params)
    @list.user = current_user
    @new_list = List.new

    if @list.save
      flash[:notice] = "Your list was saved successfully."
    else
      flash.now[:alert] = "Error creating list. Please try again."
    end

    respond_to do |format|
      format.js
    end
  end

As someone relatively new to Ruby with minimal experience in JavaScript, any guidance or insights on where I might be making mistakes would be greatly appreciated. The newly created list does get generated, it just doesn't display until the page is manually refreshed.

Answer №1

It appears that there is an incorrect variable name used in the file create.js.erb. The validation should be performed on @list instead of @item.

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

Invoke a function from a different vue.js component using the this.$refs property

I'm facing an issue with triggering a sibling element. What I've tried so far <b-img @click="callFileLoader"/> <b-file type="file" ref="fileUploader"></b-file> ... methods:{ callFileLoader () { this.$refs.fileUploader.c ...

What is the process for creating a folder using Firebase Cloud Functions with Storage?

How do I create a folder named "posts"? Storage bucket path --> gs://app.appspot.com/posts Code to generate thumbnail from storage object exports.generateThumbnail = functions.storage.object() .onChange(event => { const object = event.data ...

Collapse the active panel on a jQuery accordion with a click event

I'm currently utilizing the Simple jQuery Accordion created by CSS-Tricks, and I am seeking guidance on how to enable the active panel to close when clicking on the link within the dt element. The scenario where I am implementing this is as a menu in ...

After integrating Redux into React, the map(item) function is unable to send "item" as props to a JSX component

Currently, I am working on integrating Redux into my React application. As part of this process, I have developed four actions to manage the "items" in my application. The initial three actions, namely GET_ITEMS, DELETE_ITEM, and ADD_ITEM, function seamles ...

Implementing a dynamic like functionality using Ajax in Django

I've created a new structure for the like button, but it's not functioning correctly. Here are the files I'm working with: models.py class Comment(models.Model): title = models.CharField(max_length=50) author = models.ForeignKey(Pr ...

In JQuery, an empty string will be returned if it contains the dollar sign character

In the scenario presented here, the value is retrieved accurately with the exception of when it includes a $ symbol at the beginning (e.g. $25.00), in which case it consistently results in an empty string. HTML: <input type="number" class="form-contro ...

Troubleshooting problems with deploying an Angular app on Heroku

When I attempt to deploy my Angular app on Heroku, I am running into a 'Not found' error and getting additional information in the console ("Failed to load resource: the server responded with a status of 404"). Below is the entire Heroku build l ...

Error: Attempted to bootstrap Angular multiple times

While developing an app using angularjs, everything functions correctly after loading a web page. However, a message appears on the console saying: WARNING: Tried to load angular more than once. Upon checking the angular.js file, I found this code snippe ...

Error: discord-webhooks causing SyntaxError due to an unexpected identifier in JavaScript code

I am currently working on a javascript project to set up a webhook for Discord. The URL has been removed for privacy reasons. const DiscordWebhook = require("discord-webhooks"); let myWebhook = new DiscordWebhook("removedtopostonstackexchange") myWebhook. ...

How to retrieve the ID of a parent sibling using jQuery DataTables

I have encountered a peculiar issue while trying to retrieve the ID of a table's parent sibling. Prior to initializing jQuery DataTables, obtaining the table's ID poses no problem. However, once it is initialized and the table is built, retrievin ...

What is the best way to locate the offspring of a parent div using its data attribute?

If I have a container div called dvMainDiv with multiple child divs inside it, all added programmatically, how can I retrieve a specific child div based on its data-id attribute? <div id="dvMainDiv" class="dvMainDiv"> <div id="dvChildDiv" cla ...

I'm facing an issue with duplicate rows in my jQuery datatable

I am encountering an issue with duplicate rows in a jQuery datatable. Some rows are appearing on multiple pages when I retrieve the data using Ajax call: I have tried using this query... How can I resolve these bugs and should I utilize the unique() metho ...

Employing on() for triggering a form submission

I am attempting to attach a submit event handler to a form that may not always be present in the DOM, so I am using .on(): $('body').on("form","submit", function(e){}) However, when checking Firebug, it shows: $("body").on is not a function ...

React components are failing to display data as expected

I need to display certain data based on the id provided in the url. When I use console.log() with res.json, I can see the data but I'm unsure how to pass it to the 'articleComponent'. const Articles = () => { const query = (id) => ...

Utilizing Next.js to conditionally display data

My current challenge involves rendering data fetched from an API. The data is in JSON format, and I have a conditional logic to push a specific element based on the fetch result. {status: 'success'} If the fetch fails, I need to handle it by pus ...

Is there a way to invoke a method in Jest Enzyme without using .simulate()?

During my unit testing for a React flight seat selection application using Jest/Enzyme, I encountered a scenario where I need to test a method within my class-based component that runs after a button is clicked. However, the button in question resides deep ...

Ways to retrieve an array following a function call

After a lot of testing and troubleshooting, I finally got my array to function properly in the console. However, when I click the button, the array is displayed on the console but not in my HTML. TS: jogar(){ for(var u=0;u<6;u++){ this.y ...

What's the most effective approach to verify if all visible input fields possess a value? (excluding the use of jQuery validator

In order to ensure that all necessary fields are selected, I need to implement a check upon clicking a button. Below is the HTML code: <input type="text" class="required-entry"> <input type="text" class="required-entry"> <input type="text" ...

Is there a way to retrieve posts by year and month using nextjs and contentful?

Currently, I am in the process of setting up a blog using Next.js and Contentful CMS. The structure of my folders is set as follows: pages/blog/[year]/[month]/[slug].js Each year and month folder contains its own index.js file. Currently, my focus is on ...

Is it possible for the relative path of a gif image to become invalid when added to a div?

Question Context: In the view, I have a form that will show a loading 'spinner' gif when a user submits it. The Problem: If I place the spinner img element within its container div, the spinner is always displayed, which is not desired: https ...