Filtering records by a joined association in Rails using Ajax

My goal is to enable an end user to filter a data grid based on an associated record. The data grid currently displays a list of Activities:

The model for activity.rb (the list of records)

class Activity < ApplicationRecord
    belongs_to :student
    belongs_to :user
end

The model for student.rb (the filtering criteria)

class Student < ApplicationRecord
    belongs_to :user
    has_many :activities
    validates_attachment_content_type :image, :content_type => ["image/jpg", "image/jpeg", "image/png", "image/gif"], :convert_options => "-auto-orient"
    validates :firstname, :presence => true

end

Within the view in index.html.erb:

<heading>

    <h1 class="activity">Activity</h1>

    <div class="filter">
        <%= collection_select :students, :ids, Student.where(user_id: current_user), :id, :firstname, {}, {:onchange => '$.get("/filter_students")'} %>
    </div>

    <div class="left">
        <div class="timeblock">
            <div class="label">Date</div>
            <div class="value"><%= activity.created_at.strftime("%b %e") %></div>
        </div>
        <div class="student-name"><%= activity.student.try{|s| s.firstname} || "Deleted Student" %></div>
        <%= activity.name %>
    </div>

...

Additionally, in my activities_controller.rb:

def index
    @activities = Activity.where(user_id: current_user).order('created_at DESC').limit(50)
end
def filter_students
    @activities = Activity.find(params[:id])
    respond_to do |format|
      format.js { render 'student_activites', :formats => [:js] }
    end
end

Even though I'm able to retrieve a dropdown with students' first names, when I select one, I encounter this JavaScript error:

GET http://localhost:3000/filter_students 404 (Not Found)

Edit Here are the routes defined:

Rails.application.routes.draw do
  resources :activities
  resources :students
end

Answer №1

The app is currently fetching the URL from: http://localhost:3000/filter_students. To be more specific, it should be changed to: http://localhost:3000/activities/filter_students, indicating the controller for the action. Make sure to include the controller in your onchange directive within the collection_select.
Furthermore, you must inform Rails about the existence of a route named filter_students within the ActivitiesController that is linked to a collection. For example, if the filter student function is not associated with a particular activity, add the following lines to your routes.rb:

resources :activities do
  collection do
    get :filter_students
  end
end
resources :students

Answer №2

Make sure to include the filter_students route in your code:

add a route for 'filter_students' that points to controller action 'activities#filter_student'

Answer №3

After reviewing the current implementation of your filter_students method within the activities_controller, I suggest making the following changes:

routes.rb

# To properly utilize params[:id] in filter_students, define a member route for activities
## This allows passing params[:id] through the member do block as shown below:
resources :activities do
  member do
    get :filter_students
  end
end
resources :students

Subsequently, incorporate activity.id into the URL to reference the specific activity.

index.html.erb - updated 1/3/17

<%# Update the onchange URL format to /activity/:id/filter_students %>
<%# Ensure compatibility with the configured routes and controller logic %>
<%= collection_select :students, :ids, Student.where(user_id: current_user), :id, :firstname, {}, {:onchange => '$.get("/activity/<%= activity.id %>/filter_students")'} %>

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

Tips for avoiding the exposure of full user models in the jade template

As I work on the login functionality of my project, I'm utilizing express, passport-local, and mongoose. My code includes a series of routes: module.exports = function (app) { app.get('/', function (req, res) { res.render(' ...

Why is it beneficial to define a function as an immediately invoked function expression that returns another function?

The pattern of using IIFE (Immediately Invoked Function Expression) in three.js source code is quite common. Interestingly, removing the IIFE doesn't seem to have any impact on the functionality. It appears that using a named function instead of an an ...

The passing of query string parameters from JavaScript to a PHP processing script is ineffective

I am looking to dynamically populate a jQWidgets listbox control on my webpage with data retrieved from a MySQL database table once the page has finished loading and rendering. PARTIAL SOLUTION: You can find a solution here. NEW PROBLEM: I have created a ...

Choose dropdown choices using Node.js, MySQL, and EJS

I am looking to create a dropdown list using data from my MySQL database. Specifically, I want to populate the names from the "customer" table in the select option of my "create budgets" form using EJS. However, I am encountering issues with passing EJS da ...

After reducing the size of the table, the data spills over

Hey there, amazing individuals of the internet! Hope you're all doing well today. I've encountered a rather perplexing issue that's got me stumped. So, here's the situation - I have this table full of data and I want it to initially be ...

Is there a way to retrieve the input element's value within the controller using ng-if?

After clicking on the submit button, I want the ng-if condition to activate in the DOM so that I can access the properties of the input element or apply a class to it. <div ng-app="myModule"> <div ng-controller="myController"> <div ng-if ...

Manipulating variables across various methods in TypeScript

I have a simple code snippet where two variables are defined in the Main method and I need to access them from another method. However, I am encountering an issue with 'variables are not defined', even though I specified them in the declerations ...

invoking a function by utilizing nested controllers

Struggling with nested controllers, the main goal of this code is to link data extracted from a .json file to another function or file. .html file: <div ng-app="myApp" ng-controller="GetCtrl" > <li ng-controller="ChannelCtrl" ng-repeat="x in ...

The React-native application initialized using npx create-react-app encountered an error and could not launch

Hello there, A couple of months back, I developed an app using create-react-app. However, when I tried to run it with npm start, I encountered the following error message: react-scripts start It seems like there's an issue with the project depende ...

Can a new class be created by inheriting from an existing class while also adding a decorator to each field within the class?

In the following code snippet, I am showcasing a class that needs validation. My goal is to create a new class where each field has the @IsOptional() decorator applied. export class CreateCompanyDto { @Length(2, 150) name: string; @IsOptional( ...

Redux - Refreshing the subtree state

How can I properly reset the subtree of a redux store without resetting the entire store? I want to target only the reducer subtree in question. Check out this example code: //initial state const initialState = { isFetching: false, error: '& ...

Postman Guide: Mastering the Evaluation of JSON Arrays

One of the features in Postman allows users to save a specific field from the response body as a variable and then utilize that variable in a subsequent call. For instance, after my initial call to the web service, the response body contains: [ { "id" ...

Is it possible to launch a hidden tab or window and automatically submit the form within that tab/window?

I have a form for adding users to my Application. After submitting the form, I want to open a hidden TAB/WINDOW where another form is displayed with values retrieved from the database being written to a file. I need this second form to be automatically su ...

Looking to update the display of an array received in JSON format and then show it using ng-repeat?

Upon receiving a response from the backend, I am saving it in a variable called "allinfo" in my controller. The data received includes the name, date of birth, and hobby of a person. The hobby is an array that can contain any number of elements. In my vie ...

transferring information from PHP to JavaScript through the use of JSON encoding

I am currently in the process of developing a Google maps page that utilizes latitude and longitude data coordinates to generate a heat map displaying the distribution of foxes within a specific area. At present, my application functions properly when the ...

What is the reason behind this being deemed as true?

Imagine we have this snippet of code: var attachRed = false; Why is attachRed = !attachRed equivalent to true? I'm curious because I'm working with Vue.js and trying to grasp why this particular piece of code functions as it does. <div id= ...

I have an empty array that needs to be filled with numbers

Currently, I am facing a challenge where I have an empty array and need to insert numbers from 1 to 20 into it. Once that is complete, the next step is to calculate the total sum of all these numbers. The stumbling block I am encountering lies in this sect ...

Getting the parameters of a path from the URL's breadcrumb in Vue.js

Currently utilizing Vue Attempting to include path parameters in breadcrumb URLs for my app's router. Looking to achieve something similar to the following: { path: 'pages/gestion/region/:reg', name: 'gestion-depa', ...

What could be causing this JavaScript code not to run?

Help needed! I'm a student struggling to diagnose the issue in my code. Whenever I click the buttons, nothing happens at all. I've tried debugging by isolating each function, but still can't seem to figure it out. I've searched through ...

What is the reason behind needing to restart the server each time I make a change to my React application?

I'm diving into my first project using React, stepping away from my usual tools of pure HTML, JavaScript, PHP, and Node.js. I decided to create a single-page application portfolio, but I've encountered a frustrating issue. Every time I make a cha ...