Rails Scaffold Index Filtering - ruby

I am working on a CAD app (Rails 4, Ruby 2.2). On the Calls index Page I have 2 panels side by side.
My goal is to sort the panels into Active and Unassigned based on a DB attribute, which is currently names Status and is a "string"
I'm just not sure how to do this at all I've tried to search it out with not much luck. I am using Postgresql as my DB and below is the code for the index page I have not modified my controller but i will add the code for reference.
Index.html.erb code:
<div class="panel panel-success" id="active-pnl">
<div class="panel-heading"><center><h4>Assigned Calls: </h4></center></div>
<table class="table" id="assign-table">
<thead>
<tr>
<th><center>Call Number</center></th>
<th><center>Address</center></th>
<th><center>Responding</center></th>
<th><center>Call Type</center></th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<% #calls.each do |call| %>
<tr>
<td><center><%= call.call_num %></center></td>
<td><center><%= call.address %></center></td>
<td><center><strong><%= call.unit_1 %></strong> | <%= call.unit_2 %> | <%= call.unit_3 %> | <%= call.unit_4 %></center></td>
<td><center><%= call.primary_type %> | <%= call.secondary_type %></center></td>
<td><center><%= link_to 'View', call, class: 'btn btn-success btn-sm', id: 'view-btn' %></center></td>
<td><center><%= link_to 'Update', edit_call_path(call), class: 'btn btn-primary btn-sm', id: 'update-btn' %></center></td>
<td><center><%= link_to 'Cancel', call, class: 'btn btn-danger btn-sm', id: 'cancel-btn', method: :delete, data: { confirm: 'Are you sure?' } %></center></td>
</tr>
<tr>
</tr>
<% end %>
</tbody>
</table>
</div>
<div class="panel panel-danger" id="unactive-pnl">
<div class="panel-heading"><center><h4>Unassigned Calls:</h4></center></div>
<table class="table" id="nonassign-table">
<thead>
<tr>
<th><center>Call Number</center></th>
<th><center>Address</center></th>
<th><center>Status</center></th>
<th><center>Call Type</center></th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<% #calls.each do |call| %>
<tr>
<td><center><%= call.call_num %></center></td>
<td><center><%= call.address %></center></td>
<td><center><%= call.status %></center></td>
<td><center><%= call.primary_type %> | <%= call.secondary_type %></center></td>
<td><center><%= link_to 'View', call, class: 'btn btn-success btn-sm', id: 'view-btn' %></center></td>
<td><center><%= link_to 'Update', edit_call_path(call), class: 'btn btn-primary btn-sm', id: 'update-btn' %></center></td>
<td><center><%= link_to 'Cancel', call, class: 'btn btn-danger btn-sm', id: 'cancel-btn', method: :delete, data: { confirm: 'Are you sure?' } %></center></td>
</tr>
<% end %>
</tbody>
</table>
</div>
<br>
<center>
<%= link_to new_call_path, class: "btn btn-success btn-lg", id: 'newcall-btn' do %>
<i class="glyphicon glyphicon-plus"> NewCall</i>
<% end %>
</center>
Calls Controller:
class CallsController < ApplicationController
before_action :set_call, only: [:show, :edit, :update, :destroy]
# GET /calls
# GET /calls.json
def index
#calls = Call.all
end
# GET /calls/1
# GET /calls/1.json
def show
end
# GET /calls/new
def new
#call = Call.new
end
# GET /calls/1/edit
def edit
end
# POST /calls
# POST /calls.json
def create
#call = Call.new(call_params)
respond_to do |format|
if #call.save
format.html { redirect_to #call, notice: 'Call was successfully created.' }
format.json { render :show, status: :created, location: #call }
else
format.html { render :new }
format.json { render json: #call.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /calls/1
# PATCH/PUT /calls/1.json
def update
respond_to do |format|
if #call.update(call_params)
format.html { redirect_to #call, notice: 'Call was successfully updated.' }
format.json { render :show, status: :ok, location: #call }
else
format.html { render :edit }
format.json { render json: #call.errors, status: :unprocessable_entity }
end
end
end
# DELETE /calls/1
# DELETE /calls/1.json
def destroy
#call.destroy
respond_to do |format|
format.html { redirect_to calls_url, notice: 'Call was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_call
#call = Call.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def call_params
params.require(:call).permit(:call_time, :status, :primary_type, :secondary_type, :site, :address, :unit_1, :unit_2, :unit_3, :unit_4, :call_details, :unit_on_scene, :unit_clear, :call_num, :site_id)
end
end
So to recap: I am looking for something that will sort the calls into either of the tables based on its current status. If ACTIVE i would like it in the Active calls Table if Unassigned i would like it in the unassigned table. Any help here would be greatly appreciated.

Assume you have two values 1 and 0 in the field status of model Call. In your controller action:
def index
#active_calls = Call.where(status: 1)
#inactive_calls = Call.where(status: 0)
end
Then you can access two arrays #active_calls and #inactive_calls in your view, just replaces
<% #calls.each do |call| %>
to
<% #active_calls.each do |call| %>
or
<% #inactive_calls.each do |call| %>
based on where you would like to display them.

Related

Populate or display entries from bottom to top of the table row of the expenses table in ruby on rails

I just want to show the balance amount at the top row of the table.
index.html.erb
<p id="notice"><%= notice %></p>
<h1>Expenses</h1>
<% balance = 0 %>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
</style>
<div class="container">
<table id="table_id" style="width:100%">
<thead>
<tr>
<th>Date</th>
<th>Particulars</th>
<th>Debit</th>
<th>Credit</th>
<th>Balance</th>
</tr>
</thead>
<tbody>
<% #expenses.each do |expense| %>
<tr>
<td><%= expense.date.strftime('%d/%m/%Y') %></td>
<td><%= expense.particulars %></td>
<td class="pos"><%= expense.debit %></td>
<td class="neg"><%= expense.credit %></td>
<% balance += expense.debit.to_f-expense.credit.to_f %>
<% color = balance >= 0 ? "pos" : "neg" %>
<td class="<%= color %>"><%= number_with_precision(balance.abs, :delimiter => ",", :precision => 0) %></td>
<!--<td><%= link_to 'Show', expense %></td>-->
<!-- <td><%= link_to 'Edit', edit_expense_path(expense) %></td>-->
<!-- <td><%= link_to 'Destroy', expense, method: :delete, data: { confirm: 'Are you sure?' } %></td>-->
</tr>
<% end %>
</tbody>
</table>
</div>
<br>
<%= link_to 'New Expense', new_expense_path %>
expenses_controller.rb
class ExpensesController < ApplicationController
before_action :set_expense, only: %i[ show edit update destroy ]
# GET /expenses or /expenses.json
def index
#expenses = Expense.all
# #expenses = Expense.order("created_at ASC")
# #expenses = Expense.order("created_at DESC")
end
# GET /expenses/1 or /expenses/1.json
def show
end
# GET /expenses/new
def new
#expense = Expense.new
end
# GET /expenses/1/edit
def edit
end
# POST /expenses or /expenses.json
def create
#expense = Expense.new(expense_params)
respond_to do |format|
if #expense.save
format.html { redirect_to #expense, notice: "Expense was successfully created." }
format.json { render :show, status: :created, location: #expense }
else
format.html { render :new, status: :unprocessable_entity }
format.json { render json: #expense.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /expenses/1 or /expenses/1.json
def update
respond_to do |format|
if #expense.update(expense_params)
format.html { redirect_to #expense, notice: "Expense was successfully updated." }
format.json { render :show, status: :ok, location: #expense }
else
format.html { render :edit, status: :unprocessable_entity }
format.json { render json: #expense.errors, status: :unprocessable_entity }
end
end
end
# DELETE /expenses/1 or /expenses/1.json
def destroy
#expense.destroy
respond_to do |format|
format.html { redirect_to expenses_url, notice: "Expense was successfully destroyed." }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_expense
#expense = Expense.find(params[:id])
end
# Only allow a list of trusted parameters through.
def expense_params
params.require(:expense).permit(:date, :particulars, :debit, :credit)
end
end
I tried using #expenses = Expense.order("created_at ASC") and #expenses = Expense.order("created_at DESC") in my expense controller but unable to get the true balance.
Actually I have to display the populated entries from bottom to top with the appropriate balance entries.
Any suggestions are most welcome.
Thank you in advance.
if i understood you correctly you should move definition of balance variable into the each in index.html.erb:
<p id="notice"><%= notice %></p>
<h1>Expenses</h1>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
</style>
<div class="container">
<table id="table_id" style="width:100%">
<thead>
<tr>
<th>Date</th>
<th>Particulars</th>
<th>Debit</th>
<th>Credit</th>
<th>Balance</th>
</tr>
</thead>
<tbody>
<% #expenses.each do |expense| %>
<tr>
<td><%= expense.date.strftime('%d/%m/%Y') %></td>
<td><%= expense.particulars %></td>
<td class="pos"><%= expense.debit %></td>
<td class="neg"><%= expense.credit %></td>
<% balance = 0 %>
<% balance += expense.debit.to_f-expense.credit.to_f %>
<% color = balance >= 0 ? "pos" : "neg" %>
<td class="<%= color %>"><%= number_with_precision(balance.abs, :delimiter => ",", :precision => 0) %></td>
<!--<td><%= link_to 'Show', expense %></td>-->
<!-- <td><%= link_to 'Edit', edit_expense_path(expense) %></td>-->
<!-- <td><%= link_to 'Destroy', expense, method: :delete, data: { confirm: 'Are you sure?' } %></td>-->
</tr>
<% end %>
</tbody>
</table>
</div>
<br>
<%= link_to 'New Expense', new_expense_path %>

Ruby on Rails - update fields based on f.select value

I have a dropdown box to chose the number of tickets that one wants to buy. I want to update the fields after it to reflect the value once it is clicked. Here is a snippet of my form currently:
<%= form_for :transaction, :url => new_transaction_path(:event_id => #event.id), :method => 'GET' do |f| %>
<table style="width:100%">
<tr style="border-bottom: 1px solid #999999">
<td><h4>Number of Guests</h4></td>
<td>
<%= f.select(:quantity, (1..20))%>
</td>
</tr>
<tr style="border-bottom: 1px solid #999999">
<!-- replace (1) with the value from the f.select dropdown -->
<td><h4><%= #original_event_price %> x (1) guest(s)</h4></td>
</tr>
</table>
<%= f.submit 'Request to Book', class: 'button mt1 btn-request-to-book' %>
<% end %>
I want to replace (1) with the value from the f.select dropdown in the last table row to the value of guests that the user chooses.
EDIT WITH WORKING SOLUTION
<%= form_for :transaction, :url => new_transaction_path(:event_id => #event.id), :method => 'GET' do |f| %>
<table style="width:100%">
<tr style="border-bottom: 1px solid #999999">
<td><h4>Number of Guests</h4></td>
<td>
<%= f.select :quantity, (1..20), {}, { :onChange=>'mytest()', :id=>'quantitySelect' } %>
</td>
</tr>
<tr style="border-bottom: 1px solid #999999">
<!-- replace (1) with the value from the f.select dropdown -->
<td><h4><%= #original_event_price %> x (1) guest(s)</h4></td>
</tr>
</table>
<%= f.submit 'Request to Book', class: 'button mt1 btn-request-to-book' %>
<% end %>
SCRIPT
<script type="text/javascript">
function mytest() {
var quantity = $('#quantitySelect').val();
$('#quantityRow').html("<h4><%= #original_event_price %> x (" + quantity + ") guest(s)");
}
</script>
Problem : How to load value in other field based on drop-down selection
Solution:
<div class="field form-group">
<%= form.label :grade %>
<%= form.select(:grade, options_for_select(['A', 'B', 'C', 'D', 'E', 'F']), {:include_blank => 'Select Grade'}, class:"form-control", placeholder:"Grade", onchange: "loadRemarksBasedOnGrade()") %>
</div>
<div class="field form-group">
<%= form.label :remarks %>
<%= form.text_field :remarks, class:"form-control", placeholder:"Remarks", readonly: true %>
</div>
JavaScript :
<script type="text/javascript">
function loadRemarksBasedOnGrade() {
var grades = [];
grades['A'] = "Excellent";
grades['B'] = "Very Good";
grades['C'] = "Good";
grades['D'] = "Average";
grades['E'] = "Below average";
grades['F'] = "Failed";
let grade = document.getElementById("student_grade");
if(grades[grade.value] !== undefined) {
document.getElementById("student_remarks").value = grades[grade.value];
} else {
document.getElementById("student_remarks").value = "";
}
}
</script>
Note: So onchnage event loadRemarksBasedOnGrade update value based on id.
You can do this with jQuery:
Let's add an id: "quantitySelect" on the quantity field
Let's also add an id: "quantityRow" on the td field
$(function(){
$('.quantitySelect').change(function(e){
e.preventDefault();
var quantity = $('.quantitySelect').val();
$('.quantityRow').html("<h4><%= #original_event_price %> x (" + quantity + ") guest(s)");
});
});
You can also add if checks to see if the quantity is > 1 and append the word guest to guests.

Rails AJAX a Destroy Action

I'm trying to use AJAX on a friendships list where the "Request Friendship" button turns into a "Cancel Request" button and then back again if clicked a second time. The first click works, the ajax on the "Cancel Request" button does not.
On line 2 of the destroy.js.erb I get a:
undefined method `id' for nil:NilClass
I know it's not working because the user_id is not passed in the URL for the destroy as it is for the create, but I don't know how to fix it.
Friendships Controller
before_action :authenticate_user!
before_action :set_user, only: [:create]
before_action :set_friendship, only: [:destroy, :accept]
def create
#friendship = current_user.request_friendship(#user)
respond_to do |format|
format.html {redirect_to users_path, notice: "Friendship Requested"}
format.js
end
end
def destroy
#friendship.destroy
respond_to do |format|
format.html {redirect_to users_path, notice: "Friendship Removed"}
format.js
end
end
def accept
#friendship.accept_friendship
#friendship.create_activity key: 'friendship.accepted', owner: #friendship.user, recipient: #friendship.friend
#friendship.create_activity key: 'friendship.accepted', owner: #friendship.friend, recipient: #friendship.user
respond_to do |format|
format.html {redirect_to users_path, notice: "Friendship Accepted"}
format.js
end
end
private
def set_user
#user = User.find(params[:user_id])
end
def set_friendship
#friendship = Friendship.find(params[:id])
end
Create JS
$('.js-not-friend-btn').bind('ajax:success', function() {
$('.action-button-for-<%= #user.id %>').html('<%= j action_buttons(#user) %>');
});
Destroy JS
$('.js-cancel-request-btn').bind('ajax:success', function() {
$('.action-button-for-<%= #user.id %>').html('<%= j action_buttons(#user) %>');
});
Users Helper
def action_buttons(user)
case current_user.friendship_status(user) when "friends"
link_to "Cancel Friendship", friendship_path(current_user.friendship_relation(user)), method: :delete, :remote => true, class: "js-cancel-friendship-btn btn btn-danger btn-xs mr10"
when "pending"
link_to "Cancel Request", friendship_path(current_user.friendship_relation(user)), method: :delete, :remote => true, class: "js-cancel-request-btn btn btn-danger btn-xs mr10"
when "requested"
link_to("Accept Friendship", accept_friendship_path(current_user.friendship_relation(user)), method: :put, :remote => true, class: "js-accept-friendship-btn btn btn-success btn-xs mr10") +
link_to("Decline", friendship_path(current_user.friendship_relation(user)), method: :delete, :remote => true, class: "js-decline-friendship-btn btn btn-default btn-xs mr10")
when "not_friends"
link_to "Add as Friend", friendships_path(user_id: user.id), method: :post, :remote => true, class: "js-not-friend-btn btn btn-success btn-xs mr10"
end
end
Thanks for any help you can offer.
I had to add the following line to my destroy action in order to use #user in the destroy.js.erb:
#user = #friendship.user == current_user ? #friendship.friend : #friendship.user

Ruby on Rails, Redirect After Creating New Post in Note Taking App

In my RoR note taking application notes are called Statuses.
When a user creates and posts a new Status, I would like them to be redirected to the Satuses page, an index of all of their Statuses/Notes.
Right now they are redirected to a page that shows just that new Status/Note.
I thought this would be a simple rediect in the Statuses controller, the Create action, but it isn't. A friend coded this part of the app and the JSON and render commands there have thrown me off a bit.
Here is the code from the controller:
# POST /statuses
# POST /statuses.json
def create
#status = current_user.statuses.new(params[:status])
respond_to do |format|
if #status.save
format.html { redirect_to #status, notice: 'Status was successfully created.' }
format.json { render json: #status, status: :created, location: #status }
else
format.html { render action: "new" }
format.json { render json: #status.errors, status: :unprocessable_entity }
end
end
end
And from the entry form partial:
<%= f.text_area :content %>
<div class="row">
<div class = "small-3 small-centered columns text-center">
<%= f.submit "Post", class: "radius button text-center" %>
</div>
</div>
<% end %>
Here you are using redirect_to #status which redirects to show page of status.
To redirect to index page use following code
respond_to do |format|
if #status.save
format.html { redirect_to statuses_path, notice: 'Status was successfully created.' }
format.json { render json: #status, status: :created, location: #status }
else
format.html { render action: "new" }
format.json { render json: #status.errors, status: :unprocessable_entity }
end

Why can't I display the next three future events from my model?

I am attempted to display the next three future events from my database but the code below displays nothing. I can't see what I have done wrong.
This is the event controller:
class EventsController < ApplicationController
def show
#event = Event.where(:slug => params[:slug]).first
#future_events = Event.where('end_date > ?', Date.today).order('end_date ASC').limit(3)
General.first.get_blog
General.first.get_twitter
if #event.nil?
#event = Event.first
end
#days = [
{ speakers: #event.sessions.day1_speakers, workshops: #event.sessions.day1_workshops },
{ speakers: #event.sessions.day2_speakers, workshops: #event.sessions.day2_workshops }
]
end
end
And this is the event view:
<% #future_events.first(3).each do |e | %>
<div class="fourcol aboutColumn">
<h3><%= e.title %></h3>
<p><%= e.start_date.strftime("%e %B %Y") %>, <%= e.venue_title %></p>
<p><%= e.event_description %></p>
</div>
<% end %>
You should structure your query to return only the events you need:
Event.where('end_date > ?', Date.today).order('end_date ASC').limit(3)
Beyond that, I can't see why nothing is displayed. Can you post your entire controller method?
Update:
This is the equivalent query for Mongoid:
Event.where(:end_date.gt => Date.today).sort(:end_date => 1).limit(3)

Resources