Nishan Acharya Nishan Acharya - 2 years ago 73
Javascript Question

Button that changes database value in Rails

Part of Group show.html.erb looks like:

<% if !@pending.empty? %>
<div class="panel panel-default">
<div class="panel-heading"> <h4>Pending Approvals for Group</h4></div>
<table class="table", style="border-collapse: separate; border-spacing: 5px 1px;">
<th>User Email</th>
<% @pending.each do |individual| %>
<td><%= %></td>
<td>Accept/Reject (BUTTONS HERE)</td>
<% end %>
<% end %>

Instead of the Accept/Reject , I need to have two buttons that changes the value in the database column membership. Accept would put a value of "member" and Reject would put "denied". However, this change is in the GroupUser not Group, which is a joint table of Groups and Users.

In other words, the accept button would essentially do
<% individual.update(membership: "member")%>
and reject would do
<% individual.update(membership: "denied")%>

The button would then change to something like, Approved or Denied. I tried various options but none of them seem to work. I am not sure if/how it can be achieved with javascript or jQuery.

This is part of my attempt to create a "Join Group" request feature that allows other users to request to join a private group and gain membership.

Answer Source

All I needed was a link (button) that would pass the parameters to a controller, which would make the change according to these parameters like shown below:

Group show.html.erb

        <td><%= link_to 'Accept', {:controller => "group",
                                   :action => "decision",
                                   :id => individual.group_id,
                                   :user_id =>,
                                   :decision => "true"}, method: 'post', class: "btn btn-sm btn-success" %>

Group controller

  def decision
    @groupUser = GroupUser.where(group_id: params[:id], user_id: params[:user_id])
    if params[:decision] == "true"
      @groupUser.update(membership: "member")
      Homework.where(group_id: params[:id]).find_each do |hw|
        UserHomework.create(user_id: params[:user_id], homework_id:, admin: true, status: 'No attempt')
      @groupUser.update(membership: "denied")
    redirect_to groupshow_path(:id => params[:id])
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download