Utilizing Ajax to Transmit Particular Information on Partials in Rails

Exploring the realm of rails, I am embarking on a quest to achieve the following:

The mission at hand involves crafting a store and unstore button to save and 'un-save' events respectively. My strategy includes leveraging event attributes and current user details to locate the stored event. Through the enchantment of ajax and remote magic in rails, I aim to transform the button's behavior from store to unstore or vice versa.

In my mystical _feed.html.erb.

<% if @feed_items.any? %>
  <ul>
    <%= render partial: 'shared/feed_item', collection: @feed_items %>
  </ul>
<% end %>

Each @feed_items treasure trove holds a wealth of data (titles, categories, and more).

Within the enchanted realms of _feed_item.html.erb.

<li id="<%= feed_item.id %>" class="item">
    ...
    <div class="small-3 text-center columns">        
      <%= render 'shared/store_form', event: feed_item %>
    </div>
    ...
</li>

The magical Event symbol guides the feed_item towards the store_form.

Amidst the mysterious lands of _store_form.html.erb.

<div id="store_form_<%= event.id %>">
    <% if event.stored?(current_user) %>
        <%= render 'shared/unstore', event: event %>
    <% else %>
        <%= render 'shared/store', event: event %>
    <% end %>
</div>

Once again, a feed_item is summoned into the midst of the partial.

_store.html.erb

<%= form_for(event.storages.build(saver_id: current_user.id, 
                        organizer_id: event.user_id),
                        remote: true) do |f| %>
    <div>
        <%= f.hidden_field :organizer_id %>
        <%= f.hidden_field :saved_id, value: event.id %>
    </div>
  <%= f.submit "store" %>
<% end %>

_unstore.html.erb

<%= form_for(event.storages.find_by(saver_id: current_user.id,
                         organizer_id: event.user_id) ,
             html: { method: :delete },
             remote: true) do |f| %>
  <%= f.submit 'unstore' %>
<% end %>

create.js.erb

$("#store_form").html("<%= escape_javascript(render 'shared/store', event: event )%>")

destroy.js.erb

$("#store_form").html("<%= escape_javascript(render 'shared/unstore', event: event) %>")

Alas, when attempting to store or unstore an event, the dark forces manifest these errors.

ActionView::Template::Error (undefined local variable or method `event' for #<#<Class:0x00000004d69be8>:0x00000004d68d10>):
    1: $("#store_form").html("<%= escape_javascript(render 'shared/unstore', event: event) %>")


ActionView::Template::Error (undefined local variable or method `event' for #<#<Class:0x00000004d69be8>:0x00000004fdc6a0>):
    1: $("#store_form").html("<%= escape_javascript(render 'shared/store', event: event )%>")

I beseech thee, how can I bestow upon this specific "event" data unto the partial? Utilizing @feed_item within the create and destroy js proves challenging, for it harbors a myriad of events. Might there be a more enlightened approach to rise above this challenge?

Answer №1

When creating and deleting actions in your controller, remember to properly initialize the 'event' variable. Update 'event' to '@event' and modify your JavaScript code as follows:

$("#store_form").html("<%= escape_javascript(render 'shared/unstore') %>

It is unnecessary to add instantiated variables to render calls because Rails automatically handles this for 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

Step-by-step guide on parsing a JSON file with an array using JavaScript

I've been struggling to figure out how to read a JSON file with JavaScript that contains an array with just one element. My PHP file is functioning correctly and produces a .json file with the following content: {"posts":[["30"]]} <script src="htt ...

Exploring ways to retrieve the main project URL in ReactJS

I am currently using ReactJS and I am looking to retrieve the full path, hostname, and base URL of my project from within a component file. How can I accomplish this task? I have attempted the following code, but it is not working and is throwing the error ...

Which HTTP method is typically used for an AJAX call that sends data to an external API using POST?

Imagine this scenario: After a user signs up for your website, you want to notify an external API (such as an email service provider) about the sign-up. This notification is done asynchronously through an AJAX request from the client to your application. T ...

Despite applying the style to the image, my rotateY function is not functioning properly

I have created a unique slider feature where images rotate either 180deg or 360deg before sliding. However, I've encountered an issue that I can't seem to figure out. The slider works perfectly until the image reaches its initial position. At thi ...

VueJS: Even when disabled, clicking a button can still navigate to a different

Is there a way to prevent the button from being clickable when the current page is the first page? Although the button disables as expected, I'm still encountering an issue where the route changes when it's clicked. Code Snippet (Javascript) ...

Choosing2 ajax managing outputs

Using select2 with ajax search queries to the database is going smoothly, but there is a small issue that I am encountering. For instance, when searching through IDs in the database and start typing '111' into select2, it shows 2 rows with the I ...

Issue with passing jQuery cookie between two HTTPS pages

I am attempting to transfer a cookie between two secure HTTPS pages using jQuery cookies. The cookie is initially set on page 1 using this code: $.cookie('name', variable, { expires: 300 , secure:true}); Upon navigating to the next page, I try ...

PHP and JavaScript Form: Include the page URL in the email form when submitting

After submitting a basic form, I am struggling to include the URL of the page in the email notification to track where the user completed the form. I have attempted various solutions from this forum, but unfortunately none of them seem to work. How can I ...

`In TypeScript Angular, encountering challenges with accessing object properties`

My TypeScript object looks like this const playlist: { tracks: Array<Track> } = { tracks: new Array<Track>() }; This is the Track interface I am working with interface Track { title?: string; album?: string; artists?: string; duration? ...

Manipulating lines and positions with jQuery

I am looking to implement a feature that allows users to choose a specific region on an image using jQuery. The functionality should be similar to the tagging feature on Facebook, but with the added bonus of being able to rotate and scale the selected area ...

Electron's Express.js server waits for MongoDB to be ready before executing queries

As I work on a demo application, Express serves some React code that interacts with a MongoDB database hosted on mLab. The data is retrieved using SuperAgent calls in my main React code loaded via index.html. While everything works fine when starting the ...

Is it possible to import multiple versions of a JavaScript file using HTML and JavaScript?

After extensive research, I am starting to think that using multiple versions of the same JavaScript library on a single page is not possible (without utilizing jquery Can I use multiple versions of jQuery on the same page?, which I am not). However, I wan ...

Troubleshooting issue with refreshing selectpicker in Bootstrap-select and Vue.js

Incorporating the bootstrap-select plugin (found at ) into a ruby on rails app with Vue.js as the javascript framework has been my latest project. The goal is to have two select options where one selects a category and the other displays all available tea ...

Looking to implement multiple databases with node using MongoDB and Mongoose technology?

Hey there, I'm facing a small technical issue and need some help. I have a database named "Company" with two columns: name and DBname. Additionally, I have multiple Company databases and I want to retrieve company data based on the Company DB. In my ...

Updating state from a React mapping component: A step-by-step guide

I am working on an API that needs data filtering and then I want to place the filtered data into a state export default class ModifyPage_Single extends React.Component { constructor(props) { super(props) this.state = {data:[],idd:" ...

Vue component fails to reflect changes in state update

<div v-for="(photon, key) in $store.state.notConnected" v-bind:key="key"> <div v-if="!photon.connected"> <p>Photon is not Connected</p> </div> <div v-if="photon.connected"> <p>Photon is ...

Determine Aggregate with Click JavaScript

Currently, I am in the process of learning Javascript and am still fairly inexperienced with the language. Within my HTML code, there are two lists present. The first list allows you to select the desired product, while the second list lets you choose the ...

What is the preferred method for verifying AJAX success when the server's response is either true or false?

My server response can be either true or false. I've been attempting to determine how to check for success based on the returned value being true or false using the script below: $('form[data-async]').on('submit', function(event) ...

How to effectively compare time duration with a timer in the Laravel framework

I am managing a table that stores various job entries for employees. Each job entry includes a column for duration. I would like to trigger an alert or other event when the duration of a job has ended. My project is built using Laravel and VueJS. Below i ...

Finding distinct values in a multidimensional array using JavaScript

When working with JavaScript, I created a multidimensional array using the following code: result.each(function(i, element){ init.push({ label : $(this).data('label'), value : $(this).val(), }); }); The resulting array in ...