Displaying a collection of items using Rails, implementing form_for and integrating Ajax functionality

Looking to display a list of "Interests" for users to "follow" by clicking on a button linked to the Interest's image. Once the follow button is clicked, the Interest and its image should be removed from the list.

Attempting to use a hide function in create.js.erb file triggered by a Relationship controller when the follow button is pressed. However, the current setup only hides the first Interest in the series, not the one selected by the user. Need help in setting this up properly.

Current Controller:

class StaticPagesController < ApplicationController
  def home
    @user = current_user
    @city = request.location.city
    @interests = Interest.all
  end

Home Page:

<%= render @interests %>

Partial:

<div id="follow_form">                      
<div class="four columns portfolio-item interests">
    <div class="our-work">
        <a class="img-overlay">
        <%= image_tag interest.image_path %>
            <div class="img-overlay-div">
            <h4><%= interest.name %></h4>
            </br>
            <h5>Placeholder
            </br>
            <%= interest.desc %></h5>
            <%= form_for(current_user.relationships.build(followed_id: 
                             interest.id), remote: true) do |f| %> 
                <div><%= f.hidden_field :followed_id %></div>
                <%= f.submit "I'm interested", class: "b-black" %>
            <% end %>
            </div>
        </a>
        <h3><a href="#"><%= interest.name %></a><span>features info</span></h3>
    </div>
   </div>
</div>

create.js.erb snippet:

$("#follow_form").hide();

UPDATE: The Relationships controller for clarification:

def create
  @interest = Interest.find(params[:relationship][:followed_id])
  current_user.follow!(@interest)
  respond_to do |format|
      format.html { redirect_to(root_url) }
      format.js 
   end
end

Answer №1

In order to distinguish between the different "follow_forms" on your page, it's necessary to provide a unique identifier for each one. If not, jQuery will only target the first element and make changes to that specific form.

One suggestion is to add the "interest.id" at the end of the follow_form id to create uniqueness.

To implement this, update your partial (assuming it is named and located in /app/views/interests/_follow_form.html.erb) as shown below:

<div id="follow_form<%="#{interest.id} %>">                      
<div class="four columns portfolio-item interests">
    <div class="our-work">
        <a class="img-overlay">
        <%= image_tag interest.image_path %>
            <div class="img-overlay-div">
            <h4><%= interest.name %></h4>
            </br>
            <h5>Placeholder
            </br>
            <%= interest.desc %></h5>
            <%= form_for(current_user.relationships.build(followed_id: 
                             interest.id), remote: true) do |f| %> 
                <div><%= f.hidden_field :followed_id %></div>
                <%= f.submit "I'm interested", class: "b-black" %>
            <% end %>
            </div>
        </a>
        <h3><a href="#"><%= interest.name %></a><span>features info</span></h3>
    </div>
   </div>
</div>

This approach ensures a distinct ID for each follow_form. Then you can iterate through your interests and render a partial for each one like this:

Homepage snippet:

<% @interests.each do |interest| %>
  <%= render 'interests/follow_form', :interest => interest %> 
<% end %>

create.js.erb file:

$("#follow_form_<%= "#{@interest.id}" %>").hide())

Your controller action remains unchanged.

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

Transform a dropdown menu into an inverted footer

I stumbled upon a unique dropdown menu design that I want to tweak and reverse, making it an innovative "dropup" menu that opens from the bottom to the top. Currently, this is what I have: HTML <div class="get-started"> <a href="#" id="get-s ...

Why is my React app opening in Google Chrome instead of the API?

I have a link in my React app that is supposed to open a PDF in another page, but for some reason Google Chrome is redirecting me to the React application instead of opening the API endpoint that renders the PDF. The URL for the PDF is /api/file/:_id and m ...

troubleshooting problems with AJAX calls and routing in Angular

I am a beginner with Angular and I recently completed a tutorial on Single Page Application development using templates imported from PHP files, along with Resource and Route modules. Below is the JavaScript code from my project: (function(){ var app ...

JavaScript: How to Build a Digital Grocery List with Browser Storage

Struggling with a tough exercise question, I could use some help deciphering it. https://i.stack.imgur.com/V5he2.png Here is how I've started the code: <!DOCTYPE html> <html> <head> <title></title> <script> fun ...

What is the method for extracting a list of properties from an array of objects, excluding any items that contain a particular value?

I have an array of objects, and I want to retrieve a list with a specific property from those objects. However, the values in the list should only include objects that have another property set to a certain value. To clarify, consider the following example ...

How can I utilize JQuery to dynamically refresh a dropdown menu?

My dropdown list is initially empty: <div> <label>Boarding Point </label> <select title="Select pickup city" id="boardingDropdown"> </select> </div> I am trying to popula ...

Having issues with v-for in Vuejs? It seems to be looping multiple times

<div v-for="item in items" :key="item.id"> <div v-for="accordion in accordions" :key="accordion.title" class="line" :class="{ green: accordion.text === 'AllaboutVue', red: accordi ...

Send an array of data from the view to the Controller in CodeIgniter

I have been searching for a solution to this question. However, for some reason, my code is not functioning properly. Here is what I want to achieve: Data Array -> ajax post -> codeigniter controller(save data in DB and redirect to another page) ...

Transform basic text into nested JSON structure with JavaScript

There is a plain string in my possession which contains various conditions. const optionString = '{2109} AND ({2370} OR {1701} OR {2702}) AND {1234} AND ({2245} OR {2339})'; The goal is to transform this string into an object structured as foll ...

When working with AngularJS, you can enhance your application by implementing a global AJAX error handler if one has

Is there a way to set a global AJAX handler that will only be called if an error handler is not already defined for a specific AJAX call? Some of my AJAX calls need to execute certain logic if an error occurs (such as re-enabling a button), while others s ...

Retrieve information from a form in AngularJS without relying on two-way data binding

Utilizing two-way data binding, the code operates effectively. However, there is a stipulation - instead of using =, use <. Upon the initial launch of the application, the text inputs will contain predefined values. The objective is to enable users to ...

The package.json file engines field specifying the version with a tilde and then a greater than sign (~>)

When a package.json file includes an engines field such as this: "engines" : { "node" : "~>12" }, What is the significance of ~> in this context? ...

Discover how to generate nested dynamic routes in NextJS by linking to MongoDB data using the getStaticProps and getStaticPaths functions

Currently, I am facing a challenge with implementing dynamic paths in NextJS and I'm struggling to find a solution. Let me provide some context for better understanding. I am working on developing an ecommerce application using NextJS, and the folder ...

Choosing a class using Jquery through a For loop in Javascript

I have a group of images with a class applied to them. I am attempting to create a for loop that will iterate through the elements of this class. In Python, you can use "for element in thing" and I was curious if there is something similar in JavaScript. A ...

Ways to input data into MySQL from a dynamically created row containing multiple selections?

tableX tabX_id name value ------------------------------------ Row1 25 XnameA 1.25 Row2 26 XnameB 4.85 Row3 27 XnameA 3.25 tableY tabX_id mytabX_id multiple_tabX_id ------------- ...

Encountered issue with Ajax post request without any additional details provided

I could really use some assistance with this issue. It's strange, as Chrome doesn't seem to have the same problem - only Firefox does. Whenever I submit the form, Ajax creates tasks without any issues. My MySQL queries are running smoothly and I& ...

The act of transferring non-textual information into web-based applications

Is it possible for a user to copy and paste a selection of pixels from MSPaint into a browser-based app using JavaScript in current browsers? If not, will HTML5 make this possible in the future? Alternatively, could something like Flex or Silverlight be us ...

Testing an Angular factory that relies on dependencies using JasmineJS

I have a factory setup like this: angular.module("myServices") .factory("$service1", ["$rootScope", "$service2", function($rootScope, $service2){...})]; Now I'm attempting to test it, but simply injecting $service1 is resulting in an &ap ...

Is there a way to navigate to a newly created document?

Is there a way to automatically redirect a user to the show action of a document or post they have just created using express.js? Take a look at the following code snippet, which outlines how I am creating the document: app.post('/document/create&ap ...

Checkbox values are not being properly returned in the AJAX post request

var selectedValues = $('input:checkbox:checked').map(function() { return this.value; }).get(); $.ajax({ type: 'POST', url: 'showdata.php', data: {values : selectedValues}, success: function(response) { // Only t ...