Error encountered: Rails' remote destroy method is failing to render a view partial due to an undefined method 'id' for Photo, resulting in a

Whenever I attempt to delete an image remotely within a view, I encounter the following error:

NoMethodError (undefined method `id' for #<Photo::ActiveRecord_Associations_CollectionProxy:0x007fa826898200>):
  app/views/photos/destroy.js.erb:1:in `_app_views_photos_destroy_js_erb__997641922821004789_70180135669200'
  app/controllers/photos_controller.rb:31:in `destroy'

This is the destroy method that I am using:

def destroy 
    @photo_destroy = Photo.find_by_id(params[:id])
    @item = Item.find(@photo_destroy.item_id)
    if @photo_destroy.present?
        @photo_destroy.destroy
    end
    flash[:success] = "Photo deleted"
    @photo = @item.photos
    respond_to do |format|
        format.html { redirect_to edit_photos_url(@item)}
        format.js
    </end

Here is the relevant section of my JavaScript for destroying:

$("#photo-<%= @photo.id %>").html("<%= escape_javascript(render('photos/showpics')) %>");

And this is the partial view being utilized:

<div class="row">
<% @photo.each do |photo| %>
<li id="photo-<%= photo.id %>">
  <div class="col-sm-6 col-md-4">
    <div class="thumbnail" >
            <%= image_tag photo.image_url(:thumb) if photo.image? %>
      <div class="caption">
                <%= photo.title %>
        <p><a href="#" class="btn btn-primary" role="button"><%= link_to 'Remove', delete_photo_path(photo), method: :delete, remote: true %></a></p>
      </div>
    </div>
  </div>
  </li>
 <% end %>
</div>

I suspect there may be a disconnect between the @photo variable in the view and the destroy action in the destroy method. Is it possible to pass @photo from the method to the JavaScript, or is there a better approach to resolve this issue?

Answer №1

Revamped according to feedback.

Take a peek at this: Your @picture is a Picture::ActiveRecord_Associations_CollectionProxy and you're using it while assigning @item.pictures.

To ensure your partial functions correctly, you must obtain the id of your removed object. Here's how:

 $("#picture-<%= @picture_deleted.id %>").html("<%= j render 'pictures/showpics', {pictures: @picture} ) %>");

Don't forget to update your partial file too:

<div class="row">
 <% pictures.each do |picture| %>  # note that pictures come from the local after rendering with j render 'pictures/showpics', {pictures: @picture}
  <li id="picture-<%= picture.id %>">  
  ....

This should do the trick!

Answer №2

To address the issue, I decided to give an identifier to the row group within the showpics segment:

<div class="row" id="photo-row">

Adjusted the JavaScript code as follows:

$("#photo-row").html("<%= escape_javascript(render('photos/showpics')) %>");

As a result, all photos are now correctly updated when one is removed. Appreciate the assistance from everyone else. Thank you.

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

Having trouble with Javascript/ajax/php: data is successfully sent from server to client, but client to server communication is not working as

Apologies for the duplicate post (Admins, kindly remove the other one!). I've been receiving great assistance from you all and was hoping to seek your help once again with the following question: I am currently working on implementing AJAX by allowin ...

Can a website built on Express.js be optimized for SEO?

Would pages created with the traditional route structure provided by Express (e.g. ) appear on Google's Search Engine Results Page as they would for a Wordpress blog or PHP website using a similar path structure? ...

Laravel 8 - sweet alert functions properly, however, the ajax functionality is not functioning as expected

As a newcomer to Ajax, I am facing an issue with deleting records from the database using Sweet Alert2. Although my swal is working fine, the ajax function seems to be malfunctioning. Can anyone point out where the problem might be and suggest a solution? ...

Update a particular class following an AJAX POST request in JavaScript

After conducting extensive research, I have come here seeking your assistance with a particular issue: I am using a comment system with multiple forms on the same page (utilizing FOSCommentBundle in Symfony). My goal is to be able to post comments via Aja ...

Is the Site Header displayed depending on the scroll position and direction of scrolling?

On my website, I have a header that I want to hide when the user scrolls down 100px and show again when they scroll up 50px. I attempted to write a script for this functionality, but it doesn't seem to be working as expected. CSS /* This CSS rule w ...

Showing navigation items in Vuejs based on authentication status

In my current project, I am developing a Single Page Application (SPA) using vuejs with vuetify and integrating authentication via a laravel/passport API. The challenge I'm facing is related to conditional rendering of navigation icons based on user a ...

Typescript: Why Lines Are Not Rendering on Canvas When Using a For-Loop

What started out as a fun project to create a graphing utility quickly turned into a serious endeavor... My goal was simple - to create a line graph. Despite my efforts, attempting to use a for-loop in my TypeScript project resulted in no output. In the ...

Angular2 only supports cross-origin requests for protocol schemes

I'm currently facing an issue while following the Angular Quickstart tutorial due to a CORS error. To resolve this, I made configurations in my Windows host file located under system32/drivers/etc/: 127.0.0.1 tour-of-heroes I also configured ...

I need help on correctly retrieving the ng-model value in a controller when using it with the contenteditable directive

I've attempted using ng-change, ng-keypress, ng-keyup, and ng-keydown for this issue. Using ng-change, the ng-model value is being updated in the controller but not reflecting on the front end. However, with the other three methods, the value displa ...

hybrid application combining AngularJS with Angular 17 and above versions

I have been attempting to set up a hybrid environment with both AngularJS and Angular 1.7+ running side by side. I diligently followed all the guidelines and even created a custom webpack configuration to bundle my AngularJS and Angular files together. The ...

Guide to obtaining specific top elements from an array using JavaScript

I'm seeking assistance with sorting arrays in JavaScript. Here is an example of a sorted array: mainArray : [25 20 20 20 18 17 17 15 12 12 10 5 5 ] The mainArray may contain duplicate values. A. Dealing with duplicates Based on user input, I need ...

Struggling to make antd compatible with my create-react-app project

Exploring ant.design with create-react-app piqued my interest, so I decided to follow the steps outlined in the antd documentation. https://ant.design/docs/react/use-with-create-react-app npx create-react-app antd-demo npm add antd Within the app.js fil ...

Can a PopUp be triggered by a web service?

Using Asp.Net 4.0 I have a web application that utilizes web service methods. I am wondering if it is feasible to display a popup in order to prompt the user for information directly from a method within the web service? ...

jQuery Timepickr function is malfunctioning

I am facing an issue with implementing a timepickr element on my website. The element works perfectly in one section of the page but not in another section. I have added the necessary css files for styling… <link rel="Stylesheet" media="screen" hre ...

Animating jQuery Counter with Changing Background Color

I've implemented a Counter that counts from 0 to a specified number, and it seems to be working perfectly. However, I want to add an animation where the background color of a div height animates upwards corresponding to the percentage of the counter. ...

Storing dropdown selection in database using Laravel form and AJAX

In my controller (FocalController.php), I have generated a dropdown list using the following code: $focalData = DB::table('role_users')->orderBy('users.id','DESC') ->leftJoin('users', function($j ...

Choose Status Menu DiscordJS version 14

Is there a way to get help with changing the bot's status if it's not working properly? The value of the variable "statuses" is set as status, but the status itself does not change. Using client.user.setStatus('dnd'); can sometimes work ...

Designing a MongoDB document structure that includes subdocuments with similar properties

Currently, I am in the process of developing a referral feature and I am relatively new to MongoDB. My main issue lies in figuring out how to construct a document that contains multiple similar subdocuments - specifically, 4 email addresses. The challenge ...

"Utilizing the jQuery append method to dynamically insert an SVG element

Currently, I'm in the process of constructing a graph by utilizing svg elements and then dynamically creating rect elements for each bar in the graph through a loop. I have a query regarding how I can effectively pass the value of the "moveBar" varia ...

I tried running the sample program from the website in mongoose, but I encountered a persistent error: "TypeError: fluffy.speak is not a function."

const mongoose = require('mongoose'); main().catch(err => console.log(err)); async function main() { await mongoose.connect('mongodb://localhost:27017/test', { useNewUrlParser: true }); console.log("Connection successfu ...