Error: Missing target element || Stimulus 1.1.1 Rails 6 - ruby

I have this error 'Error: Missing target element' in console when i try to select one target.
The main idea here is to iterate through an array of web_servers and select for each controllers, a target within each instance.(the value is_available will change continuously, and I want to use action cable to monitor it).
My stimulus controller:
import { Controller } from "stimulus";
import consumer from "channels/consumer";
export default class extends Controller {
static targets = ["status"];
connect() {
console.log('Will create subscription to: channel: "ScanServersStatusChannel" web_server_id: ' + this.data.get('id'));
this.channel = consumer.subscriptions.create({ channel: 'ScanServersStatusChannel', web_server_id: this.data.get('id') }, {
connected: this._cableConnected.bind(this),
disconnected: this._cableDisconnected.bind(this),
received: this._cableReceived.bind(this),
});
}
_cableConnected() {
// Called when the subscription is ready for use on the server
console.log('_cableConnected');
console.log(this.statusTarget);
}
_cableDisconnected() {
// Called when the subscription has been terminated by the server
console.log('_cableDisconnected');
}
_cableReceived(data) {
// Called when incoming data from websocket
const element = this.statusTarget
element.innerHTML = data
}
}
My view:
<% #web_servers.each do |web_server, index| %>
<div data-controller="serverstatus" data-serverstatus-id="<%= web_server.id %>">
<tbody class="accordion">
<tr>
<td id="web-server-id"><%= web_server.id %></td>
<td><%= web_server.port_number %></td>
<td><%= web_server.address %></td>
<div data-target="serverstatus.status">
<td><%= render 'admin/dashboards/web_servers/web_server_status', web_server: web_server%></td>
</div>
</tr>
</tbody>
</div>
<% end %>
Inside the partial:
<span ><%= web_server.is_available ? 'Disponible' : 'Non disponible' %></span>

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 Scaffold Index Filtering

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.

Empty Enumeration in post method

I have this view
#model IEnumerable<ViewModelRound2>
... <snip> ...
#{
using (Html.BeginForm(new { round1Ring3Bids = Model }))
{
if (Model != null && Model.Count() > 0)
{
... <snip> ...
#for (var x = 0; x < Model.Count(); x++)
{
ViewModelRound2 viewModelRound2 = Model.ElementAt(x);
Bid bid = viewModelRound2.Bid;
string userName = #bid.User.Invitation.Where(i => i.AuctionId == bid.Lot.Lot_Auction_ID).First().User.User_Username;
<tr>
<td>
#userName
</td>
<td>
#bid.Bid_Value
</td>
<td>
#Html.EditorFor(c => c.ElementAt(x).SelectedForRound2)
</td>
</tr>
}
</table>
<div class="buttonwrapper2">
<input type="submit" value="Select"/>
</div>
}
}
}
I have a post method that this goes to when the submit button is hit
[HttpPost]
public ActionResult Round2Manager(IEnumerable<ViewModelRound2> round1Ring3Bids)
Problem is that the enumeration is always empty. Why is this?
Problem is that the enumeration is always empty. Why is this?
Because you are not respecting the wire format that the default model binder expects to bind collections.
The following:
#Html.EditorFor(c => c.ElementAt(x).SelectedForRound2)
generates absolutely wrong names for your input fields.
I would recommend you using editor templates to avoid those kind of problems:
#model IEnumerable<ViewModelRound2>
#using (Html.BeginForm())
{
if (Model != null && Model.Count() > 0)
{
<table>
#Html.EditorForModel()
</table>
<div class="buttonwrapper2">
<input type="submit" value="Select"/>
</div>
}
}
and then define a custom editor template for the ViewModelRound2 type (~/View/Shared/EditorTemplates/ViewModelRound2.cshtml) which will automatically be rendered for each element of this collection:
#model ViewModelRound2
# {
string userName = Model.Bid.User.Invitation.Where(
i => i.AuctionId == Model.Bid.Lot.Lot_Auction_ID
).First().User.User_Username;
}
<tr>
<td>
#userName
</td>
<td>
#Model.Bid.Bid_Value
</td>
<td>
#Html.EditorFor(c => c.SelectedForRound2)
</td>
</tr>
You will now notice how the text input fields have correct names:
name="[0].SelectedForRound2"
name="[1].SelectedForRound2"
name="[2].SelectedForRound2"
...
Compare this with your initial values.

problem in Adding image in MVC3

I am using this code in mVC2 and it is working Fine for me. But when i convert it into mvc3 this code give me error. Please tell me how i convert it into mvC3. The code is
<% Html.Grid(Model.MemberPagedList).Columns(column => {
column.For(x => x.Id).Named("Id");
column.For(x => x.message).Named("Message").Action(p =>
{ %>
<td> some image tag here
</td>
<td style="display: none; " id =<%= p.Id%>>
<%= p.LogMessage %>
</td>
<% });
}).RowStart((p,row) => {
if (row.IsAlternate) { %>
<tr >
<% } else { %>
<tr>
<% }
}).Sort(Model.GridSortOptions).Attributes(#class => "table-list").Render(); %>
I am Replacing <% %> with # But it is not working. I am not able to understand how i write Html Code ie <td>.....</td>
<td style="display: none;" id=<%= p.Id%>>
<%= p.LogMessage %>
</td>
in mvc3
You could use a custom column to add an image to an MVCContrib Grid:
#(Html
.Grid<MyViewModel>(Model.MemberPagedList)
.Columns(column =>
{
column.For(x => x.Id);
column.For(x => x.LogMessage);
column
.Custom(
#<text>
<span>#item.LogMessage</span>
<img src="#Url.Action("image", new { id = item.Id })" alt="" />
</text>
)
.Named("Message");
})
.Sort(Model.GridSortOptions)
.Attributes(new Hash(#class => "table-list"))
)

Resources