Dynamically displaying the column values - ruby-on-rails

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 "".

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.

Ruby on Rails: How to print contents of variable in view and make checkbox?

I am trying to create a checklist in rails using form_for. This checklist is taken from a table which I gained in the create action of my sign_ins controller:
#content = OrientationContent.where(site_id: session[:site_id])
In my view I want to use the form_for helper to iterate through the list in #content:
<%= form_for(:sign_ups ) do |f| %>
<% #content.each do |c| %>
<%= f.check_box nil %> <%= c %> <br>
<% end %>
<% end %>
However this is not working and it produces two square brackets on the page: [].
How do I go through the list and print the name while creating a check box on the left of it? The check box does not have any meaning or data, I just need it present for reference.
Solved:
In the controller, need to pluck an individual field:
#content = OrientationContent.where(site_id: 1).pluck(:content)
In the view, structure as so:
<%= form_for(:sign_ups) do |f| %>
<% #content.each do |c| %>
<%= f.check_box nil %> <%= c %> <br>
<% end %>
<% end %>

Iterate over an Active Record Relation in Rails 3.2

I have the following code:
#items = QuestionGroup.search(params[:search]).limit(50)
This returns an ActiveRecord relation. In the view I want to iterate through it so I use:
<% if #items.present? %>
<%= #items.each do |r| %>
<%= div_for r do %>
<div><%= r.subject %></div>
<% end %>
<% end %>
<% end %>
This does print r.subject to the view but it then follows it with the entire relation. e.g.
the pipe
[#<QuestionGroup id: **, subject: "the pipe", created_at: "*******", updated_at: "******"]
Why is this and how can I fix it?
Problem is here:
<%= #items.each do |r| %>
This line of code iterates over each of the relations and due to the '=' you output its content. Change it to:
<% #items.each do |r| %>
and you are good to go!

Conditional line spacing in ERb partials

This is the code for an address partial I just wrote. People might put single line addresses in either street line, company name is optional, etc... It works exactly how I want it to, but I know that checking each variable twice is ugly and terrible.
<%= "#{a.name}" unless a.name.blank? %>
<% unless a.name.blank? %> <br> <% end %>
<%= "#{a.company_name}" unless a.company_name.blank? %>
<% unless a.company_name.blank? %> <br> <% end %>
<%= "#{a.street_1}" unless a.street_1.blank? %>
<% unless a.street_1.blank? %> <br> <% end %>
<%= "#{a.street_2}" unless a.street_2.blank? %>
<% unless a.street_2.blank? %> <br> <% end %>
<%= "#{a.city}, #{a.state} #{a.zip}" %>
So, my gratuitous use of unless aside, how should I be putting in a conditional line break?
Update:
As discussed below, it is dangerous to use .html_safe on user input. If you do use a helper method as suggested below, you must also sanitize all user input on the way into the database. I've rewritten the code above as:
<% unless a.name.blank? %>
<%= a.name %>
<br>
<% end %>
<% unless a.company_name.blank? %>
<%= a.company_name %>
<br>
<% end %>
<% unless a.street_1.blank? %>
<%= a.street_1 %>
<br>
<% end %>
<% unless a.street_2.blank? %>
<%= a.street_2 %>
<br>
<% end %>
<%= "#{a.city}, #{a.state}" %> <%= a.zip %>
The redundant checking was just me overcomplicating things. I'd strongly recommend against using .html_safe in a situation like this, since you create new problems for yourself: sanitizing the input, and remembering which fields are safe. Better to not override the sensible protection Rails provides.
There are many, many ways to go about cleaning it up, but a helper would be appropriate here:
module ApplicationHelper
def format_address(a)
top = [a.name, a.company_name, a.street_1, a.street_2]
top.reject! {|s| s.blank?} # remove null and empty values
"#{top.join('<br/>')}#{a.city}, #{a.state} #{a.zip}".html_safe
end
end
Then in your view:
<%= format_address(a) %>

Loop Trick - How to show one attribute if...?

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 = ''

Resources