Strategies for refining outputs from Controller within the View

I am facing a challenge where I need to display certain elements in my View and then filter them based on user selection. I attempted to compare variables from the controller result with a JavaScript variable, but unfortunately, it seems that this approach is not feasible in this particular situation.

Here is the model I am working with:

create_table "appointments", force: true do |t|
    t.integer  "doctor_id"
    t.integer  "user_id"
    t.datetime "start_date"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.datetime "end_date"

Within my controller, I retrieve all appointments using the following code:

@appointments = Appointment.all

Next, in my View, I display all appointments as follows:

events: 
    [
    <% @appointments.each do |appointment| %>
      {
        id     : "<%= appointment.id %>",
        title  : "Reserved",
        start  : "<%= appointment.start_date.in_time_zone.strftime '%Y-%m-%dT%H:%M:%S' %>",
        end    : "<%= appointment.end_date.in_time_zone.strftime '%Y-%m-%dT%H:%M:%S' %>",
        allDay : false
      },
    <% end %>
    ],

While this setup works perfectly fine, I now have a requirement where users can select a specific doctor, and only appointments associated with that doctor should be displayed. How can I achieve this? I tried implementing a filter like this, but it does not seem to work:

events: 
    [
    <% @appointments.each do |appointment| %>
    if <%= appointment.doctor_id %> == doctor_id{
      {
        id     : "<%= appointment.id %>",
        title  : "Reserved",
        start  : "<%= appointment.start_date.in_time_zone.strftime '%Y-%m-%dT%H:%M:%S' %>",
        end    : "<%= appointment.end_date.in_time_zone.strftime '%Y-%m-%dT%H:%M:%S' %>",
        allDay : false
      },
      }
    <% end %>
    ],

Any advice or guidance on how to tackle this issue would be greatly appreciated.

Answer №1

Note: When selecting appointments for a specific doctor using a dropdown menu, you can start by triggering an ajax request upon option selection in the dropdown:

$("select").change(function() {
  $.ajax({
    type: 'POST',
    data: 'selected=' + $("select option:selected").text(),
    dataType: 'json',
    success: function(data) {
      if ($.trim(data) !== '') {
        // The returned json will contain all appointments for the selected doctor. Take necessary actions based on this data.
      }
    },
    error: function(jqXHR, textStatus, errorThrown) {
      console.log(textStatus);
      console.log(errorThrown);
    },
    url: <insert post route here>
  })
});

Below is an outline of how the controller action should be implemented:

def retrieve_doctor_id
  selected_doctor = Doctor.find(params[:selected])
  @appointments = selected_doctor.appointments.select([:id, :start_date, :end_date])
  respond_to do |format|
    format.json render :partial => "your_controller/retrieve_doctor_id", :locals => {:appointments => @appointments}
  end      
end

Modification to include in the file app/views/your_controller/retrieve_doctor_id.json.erb:

events: 
[
<% appointments.each do |appointment| %>
  {
    id     : "<%= appointment.id %>",
    title  : "Reserved",
    start  : "<%= appointment.start_date.in_time_zone.strftime '%Y-%m-%dT%H:%M:%S' %>",
    end    : "<%= appointment.end_date.in_time_zone.strftime '%Y-%m-%dT%H:%M:%S' %>",
    allDay : false
  },
<% end %>
],

If there are any errors or issues with the above code snippet, please let me know as I have not tested it yet.

Answer №2

Here's a potential solution that might help:

schedule: 
    [
    <% @appointments.select { |a| a.doctor_id == @doctor_id }.each do |appointment| %>
      {
        id     : "<%= appointment.id %>",
        title  : "Booked",
        start  : "<%= appointment.start_date.in_time_zone.strftime '%Y-%m-%dT%H:%M:%S' %>",
        end    : "<%= appointment.end_date.in_time_zone.strftime '%Y-%m-%dT%H:%M:%S' %>",
        allDay : false
      },
    <% end %>
    ],

It is important to note that the @doctor_id variable should correspond to the specific doctor you wish to filter by. However, I should mention that this method can get quite messy. It might be more efficient to utilize a JSON builder like rabl.

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

When using child_process to run a Python script in Node.js, a promise may not resolve properly if the process exits before all

Currently, I am facing an issue while trying to execute sublist3r within a node app. The script runs successfully but only displays the banner before abruptly exiting after about 5 seconds. Typically, the script should interact with the web and take approx ...

Navigate to the end of a container

Is there a method to automatically scroll to the bottom of a div when the page is loaded? I have attempted several solutions without success. If you have any insights, please share them. Thank you! ...

Having difficulty inserting an image with style="background-image:url(' ')" in Rails from the database

Hi everyone! I am new to both Rails and Stack Overflow, and I would really appreciate it if someone could guide me here. I am currently working on a test site that resembles a personal blog. It's mainly for showcasing one user's portfolio. In t ...

I keep running into an issue whenever I attempt to import material ui icons and core - a frustrating error message pops up stating that the module cannot be found

[I keep encountering this error message when attempting to utilize @material-ui/core and icons] `import React from "react"; import "./Sidebar.CSS"; import SearchIcon from "@material-ui/icons/Search"; const Sidebar = () => { return ( <> ...

Right-align each item when selecting none

Is there a way to change the style of just one of the elements select or option, without affecting the style of both? I attempted to align the select element to the right, while leaving the option elements aligned to the left. However, this did not work a ...

Dealing with changing elements using cucumber and capybara

(Click for image) I've been working on a project where I need to create a scenario to test the login feature. However, I've encountered an issue with Capybara not being able to access dynamic elements. To Reproduce the Issue: 1) Go to Redfin.co ...

Utilizing Redux dispatch to uncheck checkboxes within renderOption with Material UI Autocomplete

In the Autocomplete component, I have a checkbox that is rendered in the renderOptions prop. By using the onChange function event: object, value: T | T[], reason: string), I can retrieve the list of selected options. The value parameter will provide me w ...

Encountering an issue while setting up the ContextAPI in nextJS, where properties of undefined Provider cannot be read

I'm encountering difficulties in implementing ContextAPI with a nextjs application. The error message I keep receiving is: TypeError: Cannot read properties of undefined (reading 'Provider') This is my approach to creating the context: impo ...

Utilizing Jquery to automatically scroll to a specific div on page load by setting an

I am attempting to automatically scroll to the div specified in the URL. The URL may include one of 21 different IDs such as: url.com/test#lite1 url.com/test#lite2 url.com/test#lite3 This scrolling action should happen when the page loads (so that user ...

Formulate a multi-line string using a collection in React's JavaScript framework

I'm working on a React function that involves a set and I need to update an HTML element using the data from this set. Below is an example of my code: const updateElement = (mySet) => { document.getElementById('myId').innerHTML = Arra ...

Utilize jQuery to hide and then show elements based on text input

Recently, I came across a useful jQuery filter example that sparked my interest. To test it out, I created my live example and shared the code on CodePen (or you can check out the Fiddle if you prefer). One issue I encountered was that after entering text ...

Are there any user interface frameworks available that can replicate the aesthetic of a Mac application?

I've been searching high and low but I haven't come across any answers yet. It caught my attention that the wunderlist mac app was developed using HTML/CSS/JS, but I'm curious if they incorporated a pre-existing UI JavaScript framework into ...

Trouble with Bootstrap 5 Carousel swipe functionality: Issues arise when inner elements with overflow are involved, causing vertical scrolling to interfere with left to right swipes

I've been scouring the internet for answers to my unique issue with a Bootstrap 5 carousel. My setup is fairly basic, but I've removed the buttons and rely solely on swiping to navigate through the carousel items. When I swipe left to right, eve ...

Physically eliminate (and obliterate) a component from keep-alive

Is there a way to access and programmatically unmount a component instance loaded from Vue Route and persisted using <keep-alive> and <component>? I am working on a dynamic tab system where each tab renders a URL which displays its declared com ...

React Router malfunctioning on production environment when integrated with an Express backend

My Single Page application is built using React for the frontend and Express for the backend. Within the application, there are two main components: and . The goal is to display the component when the "/"" URL is requested, and show the component for an ...

Transitioning a NPM project to the Apache server

Recently, I successfully managed to run a simple example project by following these steps: I downloaded and installed Node.js for windows x64. I then used Git to clone the project from https://github.com/BretCameron/three-js-sample.git Next, I ran t ...

Create a PDF document using a combination of charts and tables

When I try to create a PDF file with both the chart and table embedded, only the table is showing up. Can someone please provide me with some suggestions on how to resolve this issue? JSFIDDLE LINK ...

What is the official name of the key type for the Built-in Object?

There was a built-in type that I used in the past which represented the union of all possible object keys. It was named objectKey or something similar. Here is an example: type objectKey = string | number | symbol Unfortunately, I am drawing a blank on t ...

Array insertion is not supported by Node MSSQL

I am trying to insert multiple rows at once using an array of data. Here is how my array is structured: [ [ '1234' ], [ '5678' ], [ '9123' ]... ] And here is the query code I am using: const sql = require('mssql&a ...

Material-UI: The Mystery of Missing CSS Properties

Struggling to apply a CSS class to an element from Material-UI: bw:hover { -webkit-filter: grayscale(100%); /* Safari 6.0 - 9.0 */ filter: grayscale(100%); } Tried using makeStyles: import { makeStyles } from '@material-ui/core/styles' ...