Insert between array in rails .each while loop - ruby-on-rails

I have 100 shoes with shoe names. I don't want to display all 100 in a row, I want to display 5, then a green box, then the next 5, and the same green box... but there is something wrong with my code.
<% #shoes.each.with_index(1) do |shoe, index| %>
<% while index < 101 do %>
<%= shoe.name %>
<% if index % 5 == 0 %>
<%= Green Box %>
<% end %>

You're looking for in_groups_of(x)
<% #shoes.in_groups_of(5) do |shoe_groups| %>
<% shoe_groups.each do |shoe| %>
<%= shoe.name %>
<% end %>
<%= 'Green Box' if shoe_groups.size % 5 == 0 %>
<% end %>

Your syntax is wrong in several places - the enumerator is wrong, you are missing several end statements. Also, even though index is not a reserved word, the generally accepted style for an index is a single-letter variable like i. It should be
<% #shoes.each_with_index(1) do |shoe, i| %>
<% while i < 101 do %>
<%= shoe.name %>
<% if i % 5 == 0 %>
<%= Green Box %>
<% end %>
<% end %>
<% end %>
(But personally, I would not do the index < 101 block in the view - I would make sure that the controller that generates #shoes and sends it to the view only sends 100 elements in the array)

Related

Ruby is adding weird spacing between words

My website is printing out elements such as (SnO), however, it should be printing SnO, but it is adding a weird space and it is printing like Sn O. It is adding a space between the element for no reason. My code is on the listed below.
<% saved_element = ""%>
<% sensor.base_material.elests.each_with_index do |elest, v| %>
<% if elest.element.include? "O" %>
<% saved_element = elest %>
<% else %>
<%=elest.element.split('-').last %>
<% if elest.stoich != 1 %>
<sub><%=elest.stoich.to_i%></sub>
<% end %>
<% end %>
<% if v == sensor.base_material.elests.length-1 %>
<%=saved_element.element.split('-').last%>
<% if saved_element.stoich != 1 %>
<sub><%=saved_element.stoich.to_i %></sub>
<% end %>
<% end %>
<% end %>
The code you show is full of white spaces (at the beginning of each line). Those are printed on the HTML and compacted as one space. Also, when you print a value, it adds an space at the end, you can supress that usign <%= ... -%> (note the dash at the end)
https://www.howtobuildsoftware.com/index.php/how-do/Nzr/ruby-on-rails-erb-suppressing-spaces-in-erb-template
Anyway, I would move all that logic to a helper method, that's what helper methods are for.

RoR iterate through a group/each_slice

I'm looking to get the last 5 items in an array, but to display each item individually, not as a group.
Here's what I've tried below with no success.
#array = Town.all
<% #array.each_slice(5) do |a| %>
<%= a.first %>
<%= a.second %>
<%= a.third %>
<%= a.fourth %>
<%= a.fifth %>
<% end %>
I can't figure out how to pull out a specific number of items and then to call each individual item.
The method you are looking for is in_groups_of (https://apidock.com/rails/Array/in_groups_of):
<% #towns.in_groups_of(5) do |five_towns| %>
<% five_towns.each do |town| %>
# [...]
<% end %>
<% end %>
Update: Maybe you want only the last 5 elements of the array. If so, you can simply call:
Town.all.last(5)
# => array of (max) 5 Town records
To get the last 5 items of an Array you could use last and then iterate them with each:
<%= #array.last(5).each do |a| %>
...
<% end %>
But it seems that you want to get the last 5 records of a model; in that case, you could try this instead:
#array = Town.limit(5).order('id desc')
<%= #array.each do |a| %>
...
<% end %>
... is there a way that I can have let's say the last 5 records of a
model all within one loop? maybe
<%= #array.each do | a, b, c, d, e| %>
<%= a.description %>
<%= b.description %>
<% end %>
You could use the index of each item instead of using each; for example:
#last_five = #array.last(5)
<%= last_five[0] %>
<%= last_five[1] %>
<%= last_five[2] %>
<%= last_five[3] %>
<%= last_five[4] %>
Although that wouldn't be DRY, so it will be better to stick with each.

Using variable within each function to sort_by

At the moment i'm playing around with Rails to get the hang of it and coding in general. Therefore I created my first rails app in which I want to display my games (from the game database) on one of the pages and sort them by a variable calculated within the each function. My view page looks like this (simplified):
<% #games.sort_by{|game| ???}.each do |game| %>
<p>Userexp: <%= game.userexp1 %></p>
<p>Userexpscore: <% if (game.userexp1 <= 60) %> <%= #UserexpScore = 1 %>
<% elsif (game.userexp1 > 60) %> <%= #UserexpScore = 2 %> = 2 <% end %></p>
<p>Price: €<%= game.price %></p>
<p>Pricescore: <% if (game.price <= 20) %> <%= #PriceScore = 2 %>
<% elsif (game.price > 20) %> <%= #PriceScore = 1 %> <% end %></p>
<p>Finalscore: <%= #FinalScore = #UserexpScore + #PriceScore %></p>
<% end %>
I get how i can order them by game.userexp1 or game.price but I can't figure out if it is possible to sort them by #FinalScore (without also putting the userexpscore and pricescore in the database). I was wondering if this is possible and if yes how I can do that.
Thanks in advance!
View is not proper place for business logic.
You can move score calculating logic into model, e.g.:
class Game < ActiveRecord::Base
def userexp_score
userexp1 <= 60 ? 1 : 2
end
def price_score
price <= 20 ? 2 : 1
end
def final_score
userexp_score + price_score
end
end
Then in view
<% #games.sort_by(&:final_score).each do |game| %>
<p>Userexp: <%= game.userexp1 %></p>
<p>Userexpscore: <%= game.userexp_score %></p>
<p>Price: €<%= game.price %></p>
<p>Pricescore: <%= game.price_score %></p>
<p>Finalscore: <%= game.final_score %></p>
<% end %>
I suggest you read about MVC and separation of concerns

auto increment value in each loop

In code:
<% #offers.each do |offer|%>
<%= offer.percentageOff%> <b>% OFF on order of</b>
<%= image_tag('1407951522',:size=>'10x10',:alt=>'Rs.')%>
<%= offer.amountforDiscount%>
<%= button_to 'Delete',{:action=>'destroy',:id=>offer.id},class: "" %>
<% end %>
I am new in rails. I want to show all the offers in a numbered list, I can't use database table because id is not in order. For example:
30 % OFF on order of Rs.2000
13 % OFF on order of Rs.1000
How do i achieve this?
Easiest way if you don't want to use each_with_index then You can define variable #count=0 and display, as loop occur it will be increment by 1
<% #count = 0 %>
<% #offers.each do |offer|%>
<%= #count += 1 %> #I guess you want this to show Sr.No
...... # your code
<% end %>
each_with_index way :
<% #offers.each_with_index do |offer, index|%>
<%= index + 1 %> # index starts from 0, so added 1 to start numbering from 1
...... # your code
<% end %>

Doing basic math in Rails within each "each do" loop and getting the sum

New to Rails! I have products which are associated to a campaign. Each #product has a .price and .orders_count associated to it.
What I wanted to do is multiply the .price with .orders_count for each #product, and add them all up to get a total cost for the #campaign.
Being new to Rails, wasn't sure how to do the write syntax and had the following in the view. This does the first piece, but does not add them all up at the end. Thanks for the help!
<% #products.each do |p| %>
<% if p.orders_count? %>
<%= (number_to_currency((p.price) * p.orders_count)) %>
<% end %>
<% end %>
Try setting a variable to keep track of the sum of all products, and add the product to it each time through the loop. Try this:
<% sum = 0 %>
<% #products.each do |p| %>
<% if p.orders_count? %>
<% product = (number_to_currency((p.price) * p.orders_count)) %>
<% sum += product %>
<%= product %>
<% end %>
<% end %>
The sum is: <%= sum %>

Resources