Nishan Acharya Nishan Acharya - 7 months ago 21
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;">
<thead>
<tr>
<th>User Email</th>
<th>Accept/Reject</th>
</tr>
</thead>
<% @pending.each do |individual| %>
<tbody>
<tr>
<td><%= individual.user.email %></td>
<td>Accept/Reject (BUTTONS HERE)</td>
</tr>
</tbody>
<% end %>
</table>
</div>
</div>
<% 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

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 => individual.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: hw.id, admin: true, status: 'No attempt')
      end
    else
      @groupUser.update(membership: "denied")
    end
    redirect_to groupshow_path(:id => params[:id])
  end