`Toggle admin functionality in Rails using a checkbox`

I have a parent table with an admin and superadmin field. The superadmin has the ability to assign other parents as admin or superadmin. I am looking to add checkboxes next to each parent in the list, where checking a box indicates that the parent is an admin or superadmin. If no boxes are checked, it means that the parent is neither an admin nor superadmin. How can a superadmin easily assign or remove a parent as an admin or superadmin by simply unchecking the checkbox? Please advise.

https://i.sstatic.net/YkMyg.png

Update

<td><%= check_box_tag 'admin', true, parent.admin, :onclick => 'this.form.submit()'  %></td>
<td><%= check_box_tag 'superadmin', true, parent.superadmin, :onclick => 'this.form.submit()'  %></td>

How can I uncheck the admin or superadmin checkbox to remove that parent as an admin or superadmin respectively?

Update https://i.sstatic.net/1eWvC.png

Answer №1

Here is one possible approach to implement these changes:

  • To update the check_box fields, modify them like this:

    <%= check_box_tag 'admin', true,  parent.admin, class: 'status', data: {id: parent.id, type: 'admin'} %>
    <%= check_box_tag 'superadmin', true, parent.superadmin, class: 'status', data: {id: parent.id, type: 'superadmin' }%>
  • Include this JavaScript code:

    $(".status").on('change', function(){
        var $this = $(this) 
        var parent_id = $this.data('id'); 
        $.ajax({
          url: 'status/parent/' + parent_id,
          type: 'POST',
          data: {type: $this.data('type'), value: this.checked }
        });
      });
  • Add this method in the ParentsController:

    def change_status
       @parent = Parent.find(params[:id])<br>
       if @parent.update_attributes(params[:type] => params[:value])
          redirect_to parents_path
       end
    end
  • Also, add this route in the routes.rb file:

    post 'status/parent/:id' => 'parents#change_status'

In the controller, the :id from the path will be available as params[:id]. The data sent through the ajax request will also be accessible in the params hash, hence you can use params[:type] and params[:value].

Answer №2

<%= form_tag update_status_path, :method => 'patch' do %>
 <tbody>
  <% @parents.each do |parent| %>
   <tr> 
    <td><%= link_to parent.email,parent_path(parent) %></td>
     <td><%= check_box_tag "parents[#{parent.id}][admin]", true, parent.admin, class: 'status', data: {id: parent.id, type: 'admin'} %></td>
     <td><%= check_box_tag "parents[#{parent.id}][superadmin]", true, parent.superadmin, class: 'status', data: {id: parent.id, type: 'superadmin'} %></td>
   </tr>
  <% end %>
 </tbody>

parents_controller.rb

def manage_users
    @parents = Parent.search(params[:search]).order(params[:sort]).admins
    @parents_to_update = []
end

routes.rb

get 'main-admin/manage-users', to: 'parents#manage_users'

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

angular2 and ionic2 encounter issues when handling requests with observable and promises

I am attempting to trigger an action once a promise request has been resolved, but I'm having trouble figuring out how to achieve this. After doing some research, I learned that Ionic2 storage.get() returns a promise, and I would like to make an HTTP ...

Using an image URL in a MongoDB database - a step-by-step guide

I am working on a cosmetics project website and need to create product information for each item. Each product will have an image, which I want to include by creating a URL for it and using EJS. For example, to display the image for a product, I would us ...

Dealing with a jQuery/Javascript/AJAX response: sending a string instead of an integer as a parameter to a

Trying to figure out how to handle passing integers as strings in JavaScript within an AJAX response. Here is the code snippet: message+="<td class='yellow' onclick='open_flag("+i+j+")'>"; The message variable is eventually inse ...

Guide to setting up jQuery Mobile with bower

For my project, I'm interested in utilizing jquery-mobile through bower. In order to do so, I need to execute npm install and grunt consecutively within the bower_components/jquery-mobile directory to access the minified .js and .css files. This pro ...

Ensure that when adjusting the height of a div, the content is always pushed down without affecting the overall layout of the page

My webpage contains a div element positioned in the middle of the content, with its height being adjustable through JavaScript code. I am seeking a way to manage the scrolling behavior when the height of the div changes. Specifically, I want the content t ...

Send information back to the initial website following a sequence of alternating requests

I am facing a challenge with my website's structure: On the "Client side", I have HTML / CSS / JavaScript, and on the "Server side", I have PHP. When a user interacts with the client side by clicking a button, they are redirected to a page where a s ...

Error encountered while running dev in Next.js: Unexpected JSON token 'u' at position 0

Recently, I decided to dive into learning Next.js and sought out resources like the Youtube Video Next.js Crash Course by Traversy Media and the Next.js Official Documentation for guidance. Following the tutorials, I added the simple code snippet below to ...

Automated logout feature will be enabled if no user interaction is detected, prompting a notification dialog box

Here is my working script that I found on this site. After a period of idle time, an alert message will pop up and direct the user to a specific page. However, instead of just the alert message, I would like to implement a dialog box where the user can ch ...

Guide on displaying the appropriate child "div" with jQuery?

I am facing a challenge with my two dependent dropdowns that toggle the visibility of divs based on user input. The first div is functioning correctly, however, every time the user makes a selection in the second div, it impacts the first div. $(docume ...

How to focus on an input element in Angular 2/4

Is there a way to focus on an input element using the (click) event? I'm attempting to achieve this with the following code, but it seems like there may be something missing. (I am new to Angular) sTbState: string = 'invisible'; private ele ...

How to customize the preview grid design in material-ui-dropzone

I am working on a book form page in my React app which includes an option to upload a cover photo. I opted for material-ui-dropzone from https://yuvaleros.github.io/material-ui-dropzone/ and it's working well, but I encountered an issue with the previ ...

What is the simplest way to extract only the error message?

Having this code snippet. $('div#create_result').text(XMLHttpRequest.responseText); If we look at the content of XMLHttpRequest, it shows: responseText: Content-Type: application/json; charset=utf-8 {"error" : "User sdf doesn't exist"} st ...

Guide to opening all href links in a new window

When loading HTML content parsed from an email to a frame, the issue arises when there is an href link that tries to open in the same frame. I want to modify it so that it opens in a new tab instead. Usually, setting the target to _blank in the href would ...

Discover every possible path combination

Looking to flatten an array of 1D arrays and simple elements, reporting all combinations until reaching a leaf "node." For example: // Given input array with single elements or 1D arrays: let input = [1, 2, [3, 4], [5, 6]]; The unfolding process splits pa ...

Utilize Javascript to create a function that organizes numbers in ascending order

Is there a way to modify this code so that the flip clock digits appear in ascending order rather than randomly? $( '.count' ).flip( Math.floor( Math.random() * 10 ) ); setInterval(function(){ $( '.count' ).flip( Math.floor( Math.rand ...

Issue with useEffect causing a delay in updating the state value

I'm facing an issue with a component that displays the number of people who have liked a book. The problem is, I can't seem to consistently get the correct result in my states. Here's the code snippet: ///Fetching the book details cons ...

Stop HTML5 video playback when resizing the window

I am currently working on a responsive HTML banner that includes a video using the video tag. The entire unit scales with the window size, and I have set up a breakpoint to trigger new divs when the window width is below 820px. This is achieved with the fo ...

Ways to allow scroll events on top of an overlay without passing click events

My goal is to develop a unique map annotation tool with custom controls, not relying on the built-in features of map providers. Imagine something like this: https://i.sstatic.net/70Yj7.gif I had the idea of placing a canvas over the map for this purpose ...

What could be causing my shape to not appear when I alter the variable name in three.js?

Recently, I encountered an interesting issue with some code I found on a tutorial website. The code worked perfectly when I used the variable 'canvas', but when I changed it to something else like 'canvas2', it caused unexpected behavio ...

JavaScript code to copy a specified column through the last column, and then paste it down to the last row

I have limited experience with JavaScript and I've been putting together the code I need by searching online resources and watching videos. My goal is to set multiple columns in row 4, starting from column 18 to the last column, as the active cells fo ...