Displaying a specific show action on the index page using Rails

Currently, I have an index table displaying all subscribers with a link_to that directs to the individual subscriber's show page. However, I am interested in implementing a modal that will display the show page information in front of the index page. I must admit that I have never created a modal before and I am struggling to figure it out. Initially, I found a modal code on W3, which is cool, but it requires clicking a button on the show page to render the modal. My goal is to have the modal displayed automatically when accessing the show page from the index. I know this may seem like I want someone to code for me, but I am simply seeking guidance in the right direction as I feel overwhelmed by this task. Here is some relevant code for better understanding:

Controller:

class SubscribersController < ApplicationController
  helper_method :sort_column, :sort_direction

  def index
    @search = Subscriber.search(params[:q])
    @subscriber = @search.result
    @search.build_condition if @search.conditions.empty?
    @search.build_sort if @search.sorts.empty?
  end

  def show
    @subscriber = Subscriber.find_by(params[:id])
  end

  def new
    @subscriber = Subscriber.new
  end

  def create
    @subscriber = Subscriber.new(subscriber_params)
    if @subscriber.save
      @subscriber.touch(:subscription_date)
      SubscriberMailer.welcome_subscriber(@subscriber).deliver_now
      flash[:notice] = "Subscriber Has Been Successfully Created"
      redirect_to new_subscriber_path(:subscriber)
    else
      render "new"
    end
  end

CURRENT MODAL:

<html>
<title>W3.CSS</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css">
<body class="w3-container">

<h2>subsriber</h2>

<button onclick="document.getElementById('id01').style.display='block'" class="w3-btn">Open Modal</button>

<div id="id01" class="w3-modal">
  <div class="w3-modal-content">
    <div class="w3-container">
      <span onclick="document.getElementById('id01').style.display='none'" class="w3-closebtn">&times;</span>
      <p><%= @subscriber.first_name %></p>
    </div>
  </div>
</div>

</body>
</html>

I obtained the code from the W3 website.

Any suggestions or help you can provide would be greatly appreciated! Thank you.

Answer №1

If you want to display subscriber information in a modal, one approach is to have a hidden modal at the bottom of your page. When a subscriber is clicked, an ajax call can be made to fetch the database info. The controller will then retrieve the subscriber's information and a file with the `js.erb` extension will populate the modal with that data.

# assets/javascripts/application.js

function subFetch() {
  $('.sub').click(function() {
    $.ajax(
      url: "/subscriber/" + id,
      type: "GET"
    )
  })
}
# contollers/subscribers_controller.rb

class SubscribersController
  def show
    @sub = Subscriber.find params[:id]
  end
end

This jQuery script runs after the controller action has completed its code execution.

# views/subscribers/show.js.erb

$('#modal .body').replacewith("<%= j( render 'subscribers/show') %>")
$(subFetch);

Don't forget to create a partial for the `render 'subscribers/show.js.erb'` to function correctly.

# views/subscribers/_show.html.erb

<h3><%= @sub.name %></h3>
<p><%= @sub.info %></p>

Following these steps should help guide you in implementing this feature.

Answer №2

To implement a modal in your web application, you should start by creating a file called show.js.erb. In this file, make sure to include the necessary code to trigger the modal display. Make sure to use remote true when defining the link_to for the show action to ensure that the modal is triggered via JavaScript.

Here is an example of how your link_to should look like:

link_to 'show', subscriber_path(@subscriber), remote: true

The content of your show.js.erb file should be as follows:

$("#your_global_modal_id").html("<%= j render partial: 'modal' %>");
$("#your_global_modal_id").show();

By following these steps and including this code, you will successfully integrate the modal functionality into your application.

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

Creating a stylish arrow using HTML5 and CSS

Does anyone know how to create a navigation arrow similar to the ones used on this webpage: ? I would like to incorporate it into my own website. Thank you in advance for any assistance! ...

"Implementing a where clause in an AJAX request with a date range

Here is the HTML code snippet: <div class="col-md-4 input-group input-group-lg search"> <span class="input-group-addon"><i class="fa fa-fw fa fa-calendar red"></i></span> <input id="config" class="form-control ...

Having trouble using jQuery to target the element "(this)"?

Currently, I am delving into jQuery and have stumbled upon a section that perplexes me. Due to my lack of familiarity with the terminology, conducting an effective Google search has proven difficult. Therefore, I decided to craft this question to elucidate ...

Completing a form using ajax without navigating away from the sign up page

I am new to AJAX and researching how to submit a form using this technology. My current logic involves validating the form, making an ajax request, and handling different outcomes based on server-side errors or success messages. //validate form //if inva ...

Is there a way to attach HTML buttons to the bottom of their respective cards?

I am currently in the process of creating a directory website. To build it, I chose the Jekyll Moonwalk theme as a solid foundation and am customizing it heavily to suit my requirements. Since this is my inaugural website project, I'm learning as I p ...

Guide to showcasing Laravel Eloquent information using jQuery "Ajax" tooltips?

I am new to Laravel and currently working with an index.blade.php file that contains data in table form: <table class="table table-striped"> <thead> <tr> <td>ID</td> < ...

Update the scrollspy navigation in a div with overflow by toggling the active class

Struggling to implement a navigation menu within a self-scrolling div using html/css/jquery. Looking for the menu items to toggle the active class when in view or at the top of the scrolling div. I'm essentially trying to achieve something like this ...

A recommendation feature similar to Google's auto-suggestion, implemented with AJAX and jQuery

Whenever a letter is entered into the text field and it matches a word in the database, all matching words should be displayed. For example, typing 'A' in the Travelfrom text field should show all records starting with A. The auto-complete featur ...

Resizing a column in Kendo Grid can impact the height of the grid

Take a look at this example: Whenever the column header is resized (width reduced), it causes the entire grid to shift downwards. Additionally, decreasing and then increasing the column width results in reducing the height of the entire grid. This issue p ...

Setting the maximum height for a tr or td element that is compatible with Chrome

Is there a way to set the max-height for a tr or td element that is specifically supported in Chrome? Previously, an answer suggested at this link did not work for Chrome: How to fix height of TR? ...

Tips for incorporating a custom CSS design into a jQueryUI tooltip

I am struggling to apply my custom CSS class on top of the jQueryUI tooltip. Although the tooltip is displaying correctly, my styles are not being applied. Here is the code I'm using: $(document).ready(function () { $("#roles").tooltip({ content: ...

When an input is double-clicked, the message"[object object]" appears on the screen

Here is the structure of the template used for the directive. Our code fetches data from a service which contains all the details of a specific individual. We display only the first name, last name, and either designation or company affiliation from that d ...

Retrieve the success return value from Iron-Ajax following a POST request

Currently, I am working on a project using Polymer and I am interested in retrieving the response value from an API after making a POST request with Iron-Ajax. Below is a snippet of my code: var response = $.ajax({ type: "POST", url: apiUrl, ...

What is the best way to load my CSS file using express.static?

How do I properly load my CSS file using express.static in Node.js? I have attempted various methods to link my stylesheet to my HTML file through Express, and I'm also interested in learning how to include images, JavaScript, and other assets to crea ...

Is there a way to input data when a radio button is clicked using jquery, php, and mysql?

Following the generation of a list of data in a table using PHP and MySQL, which includes radio buttons, dropdown boxes, and text boxes for each row from the database, I am hoping to implement AJAX functionality to update the database on clicking a radio b ...

Creating pathways in AJAX with Rails

Issue at hand: undefined variable article_id. The objective: Setting up the correct route for AJAX and Rails. What I require: The format articles/1/comments/2. Main goal: To specifically load comment through AJAX, not article. In the current AJAX scrip ...

Focus event in IE does not always work as expected after an ajax request is

Our current focus is on supporting IE8 exclusively. An ajax call retrieves data from the server, replaces the HTML in a container div with the response, and then attempts to focus on an element within the response. However, there seems to be inconsistenci ...

Tips for including URL in AJAX calls

Hey, I've been trying to use AJAX to pass my PHP file URL and a textbox value but it's not working. Can someone help me figure out what's wrong in my code? Here is the snippet: function displayRecords(numRecords, pageNum ) { $.ajax({ ...

Attempting to modify the Nivo slider configuration has proven to be ineffective

Can someone assist me in getting the Nivo Slider to function properly? I keep receiving a "syntax error" on the last line and can't seem to figure out what's causing it. The error occurs specifically on the line that reads: " }); " which is the ...

Tips for transferring JSON data from wicket to JavaScript

In my Java Script page, I have a function that calls Wicket Ajax: function callWicketPage() { wicketAjaxGet( urlCallback, function() {alert('success'); }, function() { alert(&apos ...