A-Z categories view - javascript

In my messages board website I want to create a page and within all the forums arranged in alphabetical order. something like Wikipedia does.
it should be dynamic (forums can be created or deleted once in a while).
How do you do that?

Here's on controller :
#grouped = {}
Forum.all.each do |forum|
# take and capitalize first character from name
letter = forum.name.slice(0,1).upcase
#grouped[letter] ||= []
#grouped[letter] << forum
end
Here's on your view :
<ul>
<% #grouped.keys.sort.each do |letter| %>
<li>
<h2><%= letter %></h2>
<ul>
<% #grouped[letter].each do |forum| %>
<li><%= forum.name %></li>
<% end %>
</ul>
</li>
<% end %>
</ul>
Source

I hope this is helpful:
1.9.3p362 :002 > ["foo", "bar", "baz", "fuzz", "debian"].group_by {|x| x[0] }
=> {"f"=>["foo", "fuzz"], "b"=>["bar", "baz"], "d"=>["debian"]}

Related

Better way to write multiple switch cases in multiple foreach methods?

I'm trying to make a web app where people can add exercises to a routine for a certain day of the week, and it'll show their entire routine on one page. I also want the names of the exercises to link to their corresponding page. So for example, my data looks like this in mongodb:
_id:60e2edf7014df85fd8b6e073
routineName:"test"
routineUsername: "tester"
monday:[{
_id: 60e430d45395d73bf41c7be8
exercise: "Bicep curls"
}{
_id: 60e4329592e3fa445836d983
exercise: "Overhead press"
}]
tuesday:[{
_id:60e2ee8962c0c15840ecc69b
exercise:"Hanging leg raise"
}]
..etc
I have this in EJS:
<% routine.monday.forEach(monday => { %>
<ul>
<% switch (monday.exercise) {
case 'Hanging leg raise' : %>
<li><%= monday.exercise %></li>
<% break;
case 'Bicep curls' : %>
<li><%= monday.exercise %></li>
<% break;
case 'Calf raises' : %>
<li><%= monday.exercise %></li>
<% break;
case 'Barbell bench press' : %>
<li><%= monday.exercise %></li>
<% break;
case 'Incline bench press' : %>
<li><%= monday.exercise %></li>
<% break;
case 'Overhead press' : %>
<li><%= monday.exercise %></li>
<% break;
case 'Barbell squat' : %>
<li><%= monday.exercise %></li>
<% break;
case 'Shrugs' : %>
<li><%= monday.exercise %></li>
<% break;
} %>
</ul>
<% }) %>
..etc
But as you can see, I have to repeat this code 7 times for every day of the week, using switch case every single time just so I can get the exercises to go to their right links. I feel like this is a terrible and inefficient way to do this, but I don't know/can't think of better ways, any help would be appreciated.
A good practice is to use objects. You can call an object like foo.bar or foo['bar'].
So start by creating an object like:
const exercices = {
'Hanging leg raise': <li>
// Fill with the rest
...
}
routine.monday.forEach(monday => { %>
<ul>
exercices[monday.exercice]
</ul>
} %>
Use this design pattern has a base for what you need.
Or
routine.monday.forEach(monday => { %>
<ul>
<a href=`/muscles/abs/${monday.exercice.trim()}`><li><%= monday.exercise %></li></a>
</ul>
} %>

Nested url queries in ruby on rails

I'm making this choose your own adventure page and I'm using form_tag to accept user input. At the start of this page a user will enter a number through this text field
<% choice_1a = "1" %>
<% choice_1b = "2" %>
<%= form_tag("/pathfinder/quest1", method: "get") do %>
<center><%= text_field_tag(:a, #input_1, maxlength: 1) %>
<%= submit_tag("Submit") %></center>
<% end %>
<% input_1 = #input_1 %>
<% if input_1 == choice_1a %>
**Run code if user entered 1 **
<%= form_tag("/pathfinder/quest1", method: "get") do %>
<center><%= text_field_tag(:b, #input_2, maxlength: 1) %>
<%= submit_tag("Submit") %></center>
<% end %>
<% elsif input_1 == choice_1b %>
**Run code if user entered 2 **
<% else %>
** Prompt user to enter a 1 or 2**
<% end %>
Which results in this output in the url of the query "a" equaling whatever input was given. In this case I entered one ("&a=1")
https://192.168.0.200:3000/pathfinder/quest1?utf8=checkmark symbol&a=1&commit=Submit
After that path is taken they are given another form_tag that shown as below
Path if 1 was chosen at form_tag "a"
<%= form_tag("/pathfinder/quest1", method: "get") do %>
<center><%= text_field_tag(:b, #input_2, maxlength: 1) %>
<%= submit_tag("Submit") %></center>
<% end %>
When they enter a number here the url would change to this. Note how "a" was replaced with "b".
https://192.168.0.200:3000/pathfinder/quest1?utf8=checkmark symbol&b=1&commit=Submit
I was hoping to somehow nest these queries so that if a=1 I can have the user set the input to "b" it would still reflect their previous input to "a"
Here's a partial of the show section of the pathfinder controller that this code is running off
Controller code
if url == ('/pathfinder/quest1')
if params[:a].present?
#input_1 = "#{params[:a]}"
elsif params[:b].present?
#input_2 = "#{params[:b]}"
end
render 'quest1/index'
What I'm trying to do is give the user the option to set a=1 and then under that branch allow b to set 1 or 2. An example of what I'm trying to accomplish
a=1 (being one path) or a=2(being the other path)
| |
V V
b=1 <---> b=2 c=1 <-----> c=2
**Different paths if the user were to set "a" to one or two**
If the user set "a" equal to one, they would have the option of setting "b" to one or two. The same concept would be for "a" equal to two where the user would only have the option of setting "c" to one or two.
I'm open to any other ideas that doesn't require changing the url if its through html, css or javascript

Get referenced objected fields from postgresql using node.js

i have tow tables in postgres database, account_invoice and res_partner. account_invoice has a relational field of res_partner referenced using id (primary key).
while querying account_invoice the res_partner is appearing as integer instead of name. to solve this i am running another query inside the account_invoice to look up for the res_partner object name field i can view that by logging in the console but cannot render it in the html.
here is my code.
<div flex class="main-container">
<%- include(page) %>
<ul>
<% markers.forEach(function (result) { %>
<li><%= result.invoice_number %></li>
<% var name = pg.search('res_partner where id = ' + result.partner_id, function(person) { %>
<% console.log(result.invoice_number + " / " + person[0].name) %>
<li><%- 'Customer name ' + person[0].name %></li>
<% }) %>
<% }) %>
</ul>
</div>

Rails - refreshing page with new table entries

The goal I am trying to achieve is to let the user click on a button which will refresh to page filter that search. My page is dedicated to music artists and would like that once the user selects "Pop", that the page refreshes showing only "pop" artists.
Here is the html + ruby that I am using to display the artists:
<% #prints the artists that match the search, prints all for empty search %>
<% #artists.each_slice(3) do |artists| %>
<div class="row">
<% artists.each do |artist| %>
<div class = "artist_images">
<%= link_to image_tag(artist.artist_art, class: 'show_image'), artist_path(artist) %><br/><br/>
</div>
<% end %>
</div>
<% end %>
<% #prints message showing that the search does not match %>
<% if !#artists.present? %>
<h3><center style = "color: white">There are no artists containing the term(s) "<%= params[:search] %>". Please try 'Adele', 'Drake', 'Kanye West', or 'Taylor Swift'</center></h3>
<% end %>
The controller has the following methods:
def index
#artists = Artist.all
end
def randomPop
#artists = Artist.where(:genre => "\nPop").random(9)
end
Does anyone know how I can go about changing the variable #artists from All artists to those in pop only through a button click?
in your view,
<%= button_to "Pop", artists_path, method: :get, params: { artist_genre: "Pop" } %>
in your controller,
def index
if params[:artist_genre]
#artists = Artist.where(:genre => params[:artist_genre]).random(9)
else
#artists = Artist.all
end
end
This classic railscast episode is on point. I would use that for how you set up your search box. The only thing you might alter/update:
if search
find(:all, :conditions => ['name LIKE ?', "%#{search}%"])
else
find(:all)
end
Should probably be a where clause based on your situation"
if search
where("genre = ?", your_genre)
else
all
end

How to break a loop with the EJS template language?

I am developping a simple web application with sails.js.
In my frontend code, i'm looping over an array of objects sent by the controller, and i am searching for a specific object. I'd like to break the loop once the object has been found. Is there a clean way to do that using the ejs template language ?
I coulnd't find anything about it on the EJS official website, nor on sails website.
I naively tried this until now :
<% objects.forEach(function(object) { %>
<% if(object.someId == someValue) {%>
<%= object.name %>
<% break %> <!-- This raise an illegal statement exception -->
<% } %>
<% } %>
The following code works as expected, but i'm looking for a cleaner solution if any
<% var found = false %>
<% objects.forEach(function(object) { %>
<% if(object.someId == someValue && !found) {%>
<%= object.name %>
<% found = true %>
<% } %>
<% } %>
It's not an EJS-related question.
break statement terminates the current loop. While you are not inside a loop. You are inside callback function, that's called by forEach method once per array element. There's no ability to interrupt forEach (see How to short circuit Array.forEach like calling break?). But, if you need it, you may use for loop for a clean solution:
<% for (var l = objects.length, i = 0; i < l; i++) { %>
<% object = objects[i]%>
<% if(object.someId == someValue) {%>
<%= object.name %>
<% break %> <!-- This will work as expected -->
<% } %>
<% } %>

Categories

Resources