Attempting to wipe out a request using ajax to access relationship entities in a ruby on rails framework

I'm currently working on implementing an ajax request to delete a "budget" (known as "orçamento" in Portuguese). These budgets are associated with a "cadastre", where each cadastre can have multiple budgets. Below, you can find the components involved:

orcamentos_controller.rb

.
.
.

    def destroy
            @cadastro = Cadastro.find(params[:cadastro_id])
            @orcamento = @cadastro.orcamentos.find(params[:orcamento_id])
            @orcamento.destroy

            respond_to do |format|
                format.js { head :ok }
            end
    end

    def index
        @cadastro = Cadastro.find(params[:cadastro_id])
        @orcamentos = @cadastro.orcamentos.paginate(page: params[:page], per_page: 10)
    end
.
.
.

index.html.erb

... <%= render "orcamentos_lista" %> ...

_orcamentos_lista.html.erb

<table class="table">
    <% @orcamentos.each do |orcamento| %>
      <tr id="remove_orcamento_<%= orcamento.id %>">
          <td>
              <%= link_to "Orçamento nº #{orcamento.id}, registrado em #{orcamento.created_at.strftime("%d/%m/%Y")}", "#", class: "list-group-item", type: 'button'%>
          </td>
          <td>
              <%= link_to "Excluir", orcamento, method: :destroy, remote: true %>
          </td>
      </tr>
    <% end %>
</table>

<% content_for :js do %>
  <% @orcamentos.each do |orcamento| %>
    $('#remove_orcamento_<%= orcamento.id %>').bind('ajax:success',
     function(){
       $('#orcamento_<%=orcamento.id%>').remove();
     }
    );
  <% end %>
<% end %>

routes.rb

.
.
.
    resources :cadastros do
      resources :orcamentos
    end
.
.
.

An error that I encounter is

undefined method orcamento_path for #<#<Class:0x007f5f39757930>:0x007f5f39cf1eb8>
specifically at this line
<%= link_to "Excluir", orcamento, method: :destroy, remote: true %>

As I am still learning Ruby and Rails, please forgive any coding mishaps or mistakes.

Answer №1

running

rake routes 

To create a link with a specific path, refer to the table of routes and use the corresponding 'prefix' followed by "_path". For example, if the resource you need is listed in the table with a prefix of foo_bar, then your link_to should include foo_bar_path in your view.

Modify this line

<%= link_to "Delete", order, method: :destroy, remote: true %>

to this

<%= link_to "Delete", foo_bar_path, method: :destroy, remote: true %>

Answer №2

You're encountering an issue because you are trying to access orcamento as a standalone resource, but it is actually nested within cadastros:

#config/routes.rb
resources :cadastros do
   resources :orcamentos # -> url.com/cadastros/:catastros_id/orcamentos/:id

This means that when calling the path helper for an orcamentos, you need to use the nested resource:

cadastros_orcamentos_path(@cadastros, orcamento)

When using link_to, you can pass an array of the nested objects as needed:

link_to "Delete", [@cadastros, orcamento], method: :delete

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

Best practice for organizing a class in Symfony2

As a newcomer to Symfony2, I am curious about the recommended approach for handling certain tasks. In my application, there are numerous administrative actions that involve receiving form data and processing it. Typically, after processing is completed, t ...

The Google Books API has reached its limit for requests

Encountering a rate limit exceeded error from the Google Books API while using this demo: To reproduce, open the developer console in Chrome and perform some searches. The rate limit errors will be displayed in the console. [],"lazyUpdate":null},"status" ...

How can the front design of Material-UI's Card header be customized?

Currently, I am facing an issue with the Material-UI card header as the background color is affecting the readability of the default font. My aim is to use the typography prop h4 for the header, but I am struggling to achieve this. https://i.stack.imgur.c ...

Organize information by time intervals using JavaScript

I am currently facing an issue where I need to dynamically sort data from the server based on different fields. While sorting is working flawlessly for all fields, I am encountering a problem with the time slot field. The challenge lies in sorting the data ...

Blend the power of Dynamic classes with data binders in Vue.js

Recently, I've been working on a v-for loop in HTML that looks like this: <ul v-for="(item, index) in openweathermap.list"> <li>{{item.dt_txt}}</li> <li>{{item.weather[0].description}}</li> <li>{{item.w ...

Having trouble displaying information in a table using React JS

I devised a feature to display one column of a table and one column for checkboxes (each row should have a checkbox). I stored this file in a component folder with the intention of creating a page where the user selects an account type, and then a new tabl ...

Export web application content to PDF through rendering on the server side

Our interactive web application, which includes multiple d3 charts, is built with vue. Currently, I am able to export our webpage to a PDF file by utilizing canvg and html2canvas to convert the content into PNG format. The PNG file is then transmitted to t ...

The jQuery Ajax function seems to be malfunctioning, while the PHP code is executing smoothly without any

I attempted to utilize AJAX to send form data to a .TXT file using PHP code. The information is successfully being added to the text file, however, the AJAX functionality is not functioning properly. Can someone please point out the error in my code? ...

Tips for optimizing the performance of a sine wave animation

After experimenting with JavaScript, I've managed to create a visually appealing sine wave animation but it's causing performance issues due to the high number of vectors being generated. My current setup involves utilizing the p5js library. Bel ...

Image Blob increases over 50 times its original size when uploaded

I'm completely baffled by the situation unfolding here. Using Preprocess.js, I am resizing/compressing an image on the front-end. During the processfile() function on the image.onload (line 32), I convert the toDataURL() string to a Blob, in order to ...

Node.js command prompt claims that 'react is non-existent'

Hello everyone! I'm excited to ask my first question on this site. I am relatively new to coding and currently learning React. Yesterday, I started working on my first project. Today, when I tried to initialize live-server and babel compiler for my J ...

What is the best method for storing objects in Firebase in order to easily rearrange them at a later time?

My list looks something like this: {"ids": [ { "id1": { "name": "name1", "lastname": "lastname1" } }, { "id2": { "name": "name2", "lastname": "lastname2" } }, { "id3": { "name": "name3", "l ...

The POST value has been identified in the raw post data, but it is not present within the php $_

Here is my unprocessed post data: ------WebKitFormBoundaryXQrRmAvDBGudXqzO Content-Disposition: form-data; name="cmd" update_cars_item ------WebKitFormBoundaryXQrRmAvDBGudXqzO Content-Disposition: form-data; name="john_id" 30 ------WebKitFormBoundaryXQr ...

When the user clicks on the login text field or password field, any existing text will

Currently, I am working on the login section of my website and I would like to implement a similar effect to Twitter's login form, where the Username and Password values disappear when the Textfield and Password field are in focus. I have attempted to ...

Is there a way I can detect a browser timeout and display a custom error message?

My webpage in classic asp contains a link to a local IP address, shown below: <a href="http://192.168.1.89">Link</a> When the local IP address is not available, the web browser eventually times out and shows its own error message. I ...

The concept of using the `map` method within a

Hi there, I could use some assistance with a tricky issue I'm facing. My current task involves rendering a cart object that includes product names, prices, and quantities. Each product can have its own set of product options stored as an array of ob ...

Press anywhere on the screen to conceal the AngularJS element

Attempting to create a toggle effect using 2 ng-click functions. One is bound to a button, the other to the body tag. The goal is for my content to show when the button is clicked and hide when anywhere on the body is clicked. However, it seems that Angul ...

Ways to combine duplicate entries within a column using Ruby on Rails?

I need some help with a filtering issue related to sign names. I am trying to merge the content together if there is more than one name of the sign. You can refer to the image attached for better clarity, where I have two server names but I only want to di ...

Eliminate the blank choice from X-editable Select

Lately, I've been dealing with AngularJS and X-editable and one thing that has been troubling me is the fact that the select option always includes an empty first child. Here's the HTML <span editable-select="curuser.roles" e-name="roles" ...

Issues with Rock Paper Scissors Array in Discord.js V12 not functioning as expected

I'm currently working on implementing an RPS game in my Discord bot. I want to create a feature where if the choice made by the user doesn't match any of the options in the list, it will display an error message. Here is the code snippet that I h ...