I have a JSON object representing a hierarchy of digital wallets:
masterWallets = {wallet: {}, childs: [{}, {}, ..., {}]}
the array of childs are other wallets which can contains other wallets... (like a file system).
Here is my html table:
<% masterWallets.forEach(function(masterWallet) { %>
<tr>
<td>masterWallet.wallet.walletName</td>
<td><%= JSON.stringify(masterWallet.childs) %></td>
<td>
<script>
document.write(window.getChilds( <%= masterWallet.childs %> ));
</script>
</td>
</tr>
<% }); %>
I would like to pass the array of child wallets (masterWallet.childs) to a function and extract and print some infos. I can see all the childs with:
<%= JSON.stringify(mWallet.childs) %>
But I can't pass this variable to my function. I have in the javascript console:
document.write(window.getChilds( [object Object],[object Object] ));
with this error:
Uncaught SyntaxError: Unexpected identifier
Question: How do I pass a JSON object (or an array of JSON objects ?) to a function ?
If your masterWallets is an object of wallet and childs then;
masterWallets = {wallet: {}, childs: [{wallet:{},childs[{}...{n}]}, ..., {n}]}
<% masterWallets.childs.forEach(function(wallet) { %>
<tr>
<td>masterWallets.wallet.walletName</td>
<td><%= JSON.stringify(wallet.childs) %></td>
<td>
<script>
document.write(window.getChilds( <%= wallet.childs %> ));
</script>
</td>
</tr>
<% }); %>
But if your masterWallets is a collection of wallets then;
masterWallets = {{wallet: {}, childs: [{}, {}, ..., {n}]},{wallet: {}, childs: [{}, {}, ..., {n}]}};
<% masterWallets.forEach(function(walletObj) { %>
<tr>
<td>walletObj.walet.walletName</td>
<td><%= JSON.stringify(walletObj.childs) %></td>
<td>
<script>
document.write(window.getChilds( <%= walletObj.childs %> ));
</script>
</td>
</tr>
<% }); %>
Related
I have tried many times but cannot resolve this syntax error.
This is a snippet of the app.js(the starting point)
const express = require('express');
const sql = require('mysql');
const ejs = require('ejs');
const app = express();
app.set('view-engine','ejs');
app.use(express.urlencoded({extended: false}));
const db = sql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'assignment'
});
db.connect((err) => {
if (err)
throw err;
console.log('Mole in');
});
app.get('/show',(req,res) => {
let sql = 'SELECT * FROM info';
let query = db.query(sql,(err,result) => {
if(err) throw err;
console.log(result,result.length);
res.render('show.ejs',{
students : result
});
})
})
This is the snippet of the ejs file where I am inserting the data that I have received from the database
<tbody>
<%
students.forEach((student)=> {
%>
<tr>
<td><%=student['Name'] %></td>
<td><%=student['Age'] %></td>
<td><%=student['Gender'] %></td>
<td><%=student['Course'] %></td>
<td><%=student['Email'] %></td>
<td><%=student['Studentid'] %></td>
<td><%=student["Marks 1"] %></td>
<td><%=student["Marks 2"] %></td>
<td><%=student["Marks 3"] %></td>
<td><%=student["Marks 4"] %></td>
<td><%=student["Marks 5"] %></td>
<td>
<button class = "btn btn-outline-danger">Edit</button>
<button class = "btn btn-outline-danger">Delete</button>
</td>
</tr>
<% }); %>
</tbody>
I think there is no syntax error here in show.ejs.
The error is because you used js code outside ejs syntax. Also, since forEach has a single argument you dont have to wrap it with brackets.
<tbody>
<% students.forEach(student => {%>
<tr>
<td><%=student['Name'] %></td>
<td><%=student['Age'] %></td>
<td><%=student['Gender'] %></td>
<td><%=student['Course'] %></td>
<td><%=student['Email'] %></td>
<td><%=student['Studentid'] %></td>
<td><%=student["Marks 1"] %></td>
<td><%=student["Marks 2"] %></td>
<td><%=student["Marks 3"] %></td>
<td><%=student["Marks 4"] %></td>
<td><%=student["Marks 5"] %></td>
<td>
<button class = "btn btn-outline-danger">Edit</button>
<button class = "btn btn-outline-danger">Delete</button>
</td>
</tr>
<% }); %>
</tbody>
I am a relative novice with rails and I am trying to use the filterrific gem for some filtering. Basically I have the index page that shows a list of vendors and I want to be able to use the filtering to actively filter/sort the records. I was able to get through the tutorial and got through all of the errors, but for some reason when you enter data into the forms, nothing happens. It is not refreshing the view at all. Any thoughts on what I am doing wrong?
Vendor Model:
filterrific(
default_filter_params: { sorted_by: 'created_at_desc' },
available_filters: [
:sorted_by,
:search_query,
:with_vendor_type_id,
:with_created_at_gte
]
)
scope :search_query, lambda { |query|
return nil if query.blank?
terms = query.downcase.split(/\s+/)
terms = terms.map { |e|
(e.gsub('*', '%') + '%').gsub(/%+/, '%')
}
num_or_conds = 2
where(
terms.map { |term|
"(LOWER(vendors.name) LIKE ? OR LOWER(vendors.bio) LIKE ?)"
}.join(' AND '),
*terms.map { |e| [e] * num_or_conds }.flatten
)
}
scope :sorted_by, lambda { |sort_option|
direction = (sort_option =~ /desc$/) ? 'desc' : 'asc'
case sort_option.to_s
when /^created_at_/
order("vendors.created_at #{ direction }")
when /^name_/
order("LOWER(vendors.name) #{ direction }, LOWER(students.bio) #{ direction }")
when /^vendor_type_title_/
order("LOWER(vnedor_types.title) #{ direction }").includes(:vendor_type)
else
raise(ArgumentError, "Invalid sort option: #{ sort_option.inspect }")
end
}
scope :with_vendor_type_id, lambda { |vendor_type_ids|
where(with_vendor_type_id: [*vendor_type_ids])
}
scope :created_at_gte, lambda { |reference_time|
where('vendors.created_at >= ?', reference_time)
}
def self.options_for_sorted_by
[
['Name (a-z)', 'name_asc'],
['Registration date (newest first)', 'created_at_desc'],
['Registration date (oldest first)', 'created_at_asc'],
['Type(a-z)', 'vendor_type_id_asc']
]
end
My Vendor Controller
def index
#filterrific = initialize_filterrific(
Vendor,
params[:filterrific],
select_options: {
sorted_by: Vendor.options_for_sorted_by,
with_vendor_type_id: VendorType.options_for_select
},
persistence_id: 'shared_key',
default_filter_params: {},
available_filters: [],
) or return
#vendors = #filterrific.find.page(params[:page])
# Respond to html for initial page load and to js for AJAX filter updates.
respond_to do |format|
format.html
format.js
end
rescue ActiveRecord::RecordNotFound => e
puts "Had to reset filterrific params: #{ e.message }"
redirect_to(reset_filterrific_url(format: :html)) and return
end
My Index View
<h1>Vendors</h1>
<%= form_for_filterrific #filterrific do |f| %>
<div>
Search
<%= f.text_field(
:search_query,
class: 'filterrific-periodically-observed'
) %>
</div>
<div>
Vendor Type
<%= f.select(
:with_vendor_type_id,
#filterrific.select_options[:with_vendor_type_id],
{ include_blank: '- Any -' }
) %>
</div>
<div>
Registered after
<%= f.text_field(:with_created_at_gte, class: 'js-datepicker') %>
</div>
<div>
Sorted by
<%= f.select(:sorted_by, #filterrific.select_options[:sorted_by]) %>
</div>
<div>
<%= link_to(
'Reset filters',
reset_filterrific_url,
) %>
</div>
<% end %>
<%= render(
partial: 'vendors/list',
locals: { vendors: #vendors }
) %>
My Partial
<div id="filterrific_results">
<div>
<%= page_entries_info vendors %>
</div>
<table>
<tr>
<th>Name</th>
<th>User ID</th>
<th>Country</th>
<th>Registered at</th>
</tr>
<% vendors.each do |vendor| %>
<tr>
<td><%= link_to(vendor.name, vendor_path(vendor)) %></td>
<td><%= vendor.user_id %></td>
<td><%= vendor.vendor_type %></td>
<td><%= vendor.created_at %></td>
</tr>
<% end %>
</table>
</div>
<%= will_paginate vendors %>
The JS file
<%# app/views/vendor/index.js.erb %>
<% js = escape_javascript(
render(partial: 'vendors/list', locals: { vendors: #vendors })
) %>
$("#filterrific_results").html("<%= js %>");
I got to the point where the from renders and got past all of the error messages, but its just not actually doing the filtering.
Include //= require filterrific/filterrific-jquery in 'app/assets/javascripts/application.js'
I'm trying to delete a "budget"(in portuguese, "orçamento") via ajax request, and that budgets have a relationship belongs to cadastre and cadastre has many budgets. My components are as follows:
orcamentos_controller.rb
.
.
.
def destroy
#cadastro = Cadastro.find(params[:cadastro_id])
#orcamento = #cadastro.orcamentos.find(params[:orcamento_id])
#orcamento.destroy
respond_to do |format|
format.js { head :ok }
end
end
def index
#cadastro = Cadastro.find(params[:cadastro_id])
#orcamentos = #cadastro.orcamentos.paginate(page: params[:page], per_page: 10)
end
.
.
.
index.html.erb
... <%= render "orcamentos_lista" %> ...
_orcamentos_lista.html.erb
<table class="table">
<% #orcamentos.each do |orcamento| %>
<tr id="remove_orcamento_<%= orcamento.id %>">
<td>
<%= link_to "Orçamento nº #{orcamento.id}, registrado em #{orcamento.created_at.strftime("%d/%m/%Y")}", "#", class: "list-group-item", type: 'button'%>
</td>
<td>
<%= link_to "Excluir", orcamento, method: :destroy, remote: true %>
</td>
</tr>
<% end %>
</table>
<% content_for :js do %>
<% #orcamentos.each do |orcamento| %>
$('#remove_orcamento_<%= orcamento.id %>').bind('ajax:success',
function(){
$('#orcamento_<%=orcamento.id%>').remove();
}
);
<% end %>
<% end %>
routes.rb
.
.
.
resources :cadastros do
resources :orcamentos
end
.
.
.
I get the error undefined method orcamento_path for #<#<Class:0x007f5f39757930>:0x007f5f39cf1eb8> this line <%= link_to "Excluir", orcamento, method: :destroy, remote: true %>
I am a beginner in both ruby as on rails, so forgive me any ugliness in code.
run
rake routes
Then whatever path you want that link to have in it find it in the table of routes and use the 'prefix' for it with "_path" at the end. So if the resource you want is on that table and has a prefix of foo_bar then your link_to should have foo_bar_path used in your view.
so change this line
<%= link_to "Excluir", orcamento, method: :destroy, remote: true %>
to this
<%= link_to "Excluir", foo_bar_path, method: :destroy, remote: true %>
The problem you have is that you're calling orcamento as the link, when you've nested it within cadastros:
#config/routes.rb
resources :cadastros do
resources :orcamentos # -> url.com/cadastros/:catastros_id/orcamentos/:id
end
This means if you want to call the path helper for an orcamentos, you have to use the nested resource:
cadastros_orcamentos_path(#cadastros, orcamento)
If you're using link_to, you should be able to pass an array of the nested objects as you require:
link_to "Delete", [#cadastros, orcamento], method: :delete
My initial view code:
view/clubs_registration/clubs/test_dropzone_pictures.html.erb
<%= render partial: 'dropzone_pictures', :locals => { :club_id => #club.id } %>
My partial code contains a hidden field:
view/clubs_registration/clubs/_dropzone_pictures.html.erb
<%= hidden_field_tag :club_id, name: :club_id, value: club_id %>
The generated HTML of my partial looks like this:
<input id="club_id" name="club_id" type="hidden" value="{:name=>:club_id, :value=>11500}">
What I really want to do is retrieve the value of club_id from my jquery:
console.log($("#club_id").val()); //-> {:name=>:club_id, :value=>11500}
I just want the value 11500.
How should I do that please?
Try setting the value key to club_id[:value]:
<%= hidden_field_tag :club_id, name: :club_id, value: club_id[:value] %>
<%= submit_to_remote(:category, :url => params[:id].blank? ? {:action => 'create'} : {:action => "update", :id => #category}) do %>
<table>
<tr>
<th>Name</th>
</tr>
<tr>
<td><%= text_field(:category, :name, :size => 20) %></td>
<td><%= submit_tag(params[:id].blank? ? "New": "Edit") %></td>
</tr>
</table>
<% end %>
I want to create new record using Ajax. I got error undefined method submit_to_remote I declared prototype file in layout.
waiting for ans.......
Firstly, it looks like your submit_to_remote is trying to define a form - so use form_for or form_tag.
Secondly submit_to_remote no longer exists in Rails 3. You need the :remote => true option of form_tag, which will let UJS (Unobtrusive JavaScript) step in and make the AJAX happen.
See some docs.