Loop Trick - How to show one attribute if...? - ruby-on-rails

I'm looking for a function we can use in a loop to do this:
<% for rink in #rinks_in_region %>
<%= rink.city #Show Only if city (n-1) != n %>
<%= link_to_rink(rink.name+" Ice Rink",rink) %>
<br>
<% end -%>
Basically just show the city only if it's different than the previous one.
Make sense? Thanks for your help!
Alextoul

You could use the group_by method on #rinks_in_region to group rinks by city and then use those groupings to display cities and rinks. It returns a hash mapping the thing you are grouping by, city in this case, to the values in the original collection that are in that group. So:
<% #rinks_in_region.group_by(&:city).each_pair do |city, rinks| %>
<%= city %>
<% rinks.each do |rink| %>
<%= link_to_rink(rink.name+" Ice Rink",rink) %>
<br/>
<% end -%>
<% end -%>

<% prev_city = nil -%>
<% for rink in #rinks_in_region %>
<%= rink.city if rink.city != prev_city %>
<% prev_city = rink.city -%>
<%= link_to_rink(rink.name+" Ice Rink",rink) %>
<br>
<% end -%>

Not a ruby answer, but introduce a new variable, call it 'temp' or something and set that to the current element in your foreach. That way at the beginning of your loop you have access to last loops element.
temp = ''
<% for rink in #rinks_in_region %>
<%= rink.city #Show Only if city != temp %>
<%= link_to_rink(rink.name+" Ice Rink",rink) %>
<br>
temp = city
<% end -%>
temp = ''

Related

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.

Rails how to make conditional inside iteration?

i'm trying to use a conditional inside a iteration but did not worked so, here the scenario:
in this case if the if the order or the product is present should just show the order and products with the feedback.
but even if is present show the feedback with odata and pdata.
someone know why?
<% #feedbacks.each do |feedback| %>
<% if order.present? && product.present? %>
<% order = feedback.order %>
<% product = order.product %>
<% else %>
<% odata = feedback.odata %>
<% pdata = odata.pdata %>
<% end %>
I guess this is what you are trying to do,
<% #feedbacks.each do |feedback| %>
<% if (order = feedback.order).present? && (product = feedback.product).present? %>
<%= order.title %>
<%= product.title %>
<% else %>
<%= (odata = feedback.odata).name %>
<%= odata.pdata.name %>
<% end %>
<% end %>
Note: title and name are assumed columns, replace it with your required/respected attribute.
Please go through this to understand the difference between various erb tags.
Comparison:
for the if condition you are trying to call order and product directly, which will throw error as they are related to feedback.
<% %> just executes the ruby code, you wanted to print the data so need to use <%= %>.
no need to save them in variable when you are not going to use it. I have saved them while checking the existence of the object in the condition and could use to display without querying the db.

Dynamically displaying the column values

Here, I have 10 columns i.e., answer1, answer2, answer3, ..., answer10 in the table MgAnswer.
I have to check whether each column value is present or not. Only if it present,then I have to display it in the page.
Im giving column names dynamically within for loop
<% (1..10).each do |i| %>
<% if MgAnswer."answer#{i}".present? %>
<%= MgAnswer."answer#{i}" %>
<% end %>
<% end %>
Im ending up with Syntax error.
You can indeed dynamically invoke methods in ruby, but this is not the syntax. Instead do
<% (1..10).each do |i| %>
<% if MgAnswer.public_send("answer#{i}").present? %>
<%= MgAnswer.public_send("answer#{i}") %>
<% end %>
<% end %>
It should seem like the following:
<% (1..10).each do |i| %>
<%= MgAnswer.send("answer#{i}") %>
<% end %>
Since ruby can't evaluate line as MgAnswer."method". Also you can just skip if condition, because it will be evaluated to empty string "".

Dont have a comma on the last iteration of an each loop in Rails

I want to print out a list of links separated by commas in Rails.
Heres what I've got:
<%= topics.each do |topic| %>
<a href="<%= topic.link %>" ><%= topic.name %></a>
,
<% end %>
Heres what I want:
Thing A,
Thing B,
Thing C
But right now I get an extra comma on the last iteration of the loop! What should I do?
One way of doing this is with map then Array#join:
<%= topics.map { |topic| link_to(topic.name, topic.link) }.join(',').html_safe %>
if you want to do minimum possible change to your code, you can use the following
<%= topics.each do |topic| %>
<a href="<%= topic.link %>" ><%= topic.name %></a>
<% if(topic != topics.last) %>
,
<% end %>
<% end %>
How about using each_with_index, and only put comma before the content unless it's not the first item.
<% topics.each_with_index do |topic, i| %>
<% if i > 0 %>
,
<% end %>
<%= topic.name %>
<% end %>
I made it in one line call (for active records collections) using the concat helper:
<% concat (',') if e.bills.last != b %>
concat is an ERB helper (TextHelper) to add some HTML without the <%= %> syntax, helpful to add few characters.
Here is the full code to make it clear:
<% event.bills.each do |b| %>
<%= link_to(b.number.to_s, bill_display_path(b)) %>
<% concat (',') if e.bills.last != b %>
<% end %>
Simply try this. It works for me
<%= topics.map{|p| p.topic.name}.join(",") %>
You can do the following to print out the comma for all items except for the last:
<% topics.each do |topic| %>
<%= topic %>
<%= "," if topic != topics.last %>
<% end %>
This will check if the current item in the loop is the last item, and will use the <%= %> syntax to output the comma.

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