How to iterate over an array of hashes? (ruby) - ruby-on-rails

How do I iterate over an array of hashes, so that I get the following type of list:
title[0]
-----
description[0]
description[1]
title[1]
-----
description[2]
description[3]
#example =
[
{title: "chapter1", description: "Hello all"},
{title: "chapter1", description: "This is an example"},
{title: "chapter2", description: "This is chapter 2"},
{title: "chapter2", description: "Another example"},
]
<% #example.each_with_index do |item, index| %>
<h1><%= item[:title] %></h1>
<p><%= item[:description] %></p>
<% end %>
How do I modify the above code so that if item[:title] == "chapter1", then it loops over the descriptions, and after that it goes through item[:title] == "chapter2" descriptions? I would like to show only the descriptions that belong to the title. Do I have to use a case...when statement, or is there a nicer way to do it?
To use the above example, I would like it to be:
<h1>Chapter 1</h1>
<p>Hello all</p>
<p>This is an example</p>
<h1>Chapter 2</h1>
<p>This is chapter 2</p>
<p>Another example</p>

You can achieve this by using group_by:
<% #example.group_by{|item| item[:title]}.each do |title,array| %>
<h1><%= title %></h1>
<% array.each do |item| %>
<p><%= item[:description] %></p>
<% end %>
<% end %>

Related

(Ruby on Rails) Displaying Posts Into Groups of 3

I'm using the following code to display posts to my users.
_feed.html.erb partial:
<% #posts_by_month.each do |monthname, posts| %>
<%= monthname %>
<ul>
<% posts.each do |post| %>
<li><%= post.created_at %></li>
<% end %>
</ul>
<% end %>
Controller:
def home
if logged_in?
#post = current_user.posts.build
#posts_by_month = current_user.feed.group_by { |post| post.created_at.strftime("%B") }
This renders my posts as follows:
Post 1
Post 2
Post 3
Post 4
I want to change it so that the posts are displayed like:
Post 1 Post 2 Post 3
Post 4 etc etc
etc
I've tried several approaches to this, including the in_groups_of(3) method however the way it is currently setup means nothing works. I feel like there is an obvious solution I'm missing - can anyone help?
[Edit to expand on the in_groups_of(3) error]
If I change line 4 in the _feed partial to:
<% posts.in_groups_of(3, false).each do |post| %>
It gives the error: undefined method `created_at' for #< Array:0xbb8f258 >
The #in_groups_of method returns an Array of Arrays each containing 3 Post objects.
So you now also need to iterate over the returned array that contains your three Posts, something like:
<% posts.in_groups_of(3, false).each do |post_group| %>
<% post_group.each do |post| %>
<li><%= post.created_at %></li>
<% end %>
<% end %>
You can use facets gem. This provides and each_by method. You can use each_by to create groups and iterate further on these groups.
Here is code snippet on how to use each_by
<div class = "small-9 columns vertical-border-left">
<%- #client.contact_details.each_by(3) do |contact_details| %>
<div class="row">
<%- contact_details.each do |contact| %>
<div class="small-3 columns small">
<div> <%= contact.contact_detail_type %> contact </div>
<div> <%= contact.contact_email %> </div>
<div> <%= contact.contact_phone %> </div>
</div>
<% end %>
</div>
<% end %>
</div>

How to stop this array of attributes from showing in my view? [duplicate]

This question already has answers here:
What is the difference between <%, <%=, <%# and -%> in ERB in Rails?
(7 answers)
Closed 3 years ago.
I have an annoying problem where my view keeps displaying an array of my object's attributes! My submenu is suppose to show categories in a tree form, which works, but it also shows this annoying array!
[ <#Category id: 26, title: "subtest", description: "a test within a test, testception", created_at: "2015-03-01 03:15:29", updated_at: "2015-03-03 01:08:09", ancestry: "6/24">]
[ <#Category id: 24, title: "Test", description: "No not be alarmed, this is only a test.", created_at: "2015-03-01 02:06:35", updated_at: "2015-03-03 01:07:52", ancestry: "6">]
I definately don't want the user to see this. How do I get rid of it??
Show.html.erb view:
<div id="submenu">
<%= render 'submenu_cats', categories: #category.root.children %>
</div>
_submenu cats partial:
<ul>
<%= categories.each do |category| %>
<li>
<%= link_to_unless_current category.title, category_path %>
<%= render 'submenu_cats', categories: category.children if category.children.present? %>
</li>
<% end %>
Using: Rails 4.2, Ruby 2.1.5, Ancestry Gem
You are using <%= %> which means that you are outputting the results of a Ruby code, instead use <% %> to executes the ruby code within the brackets.
So change
<%= categories.each do |category| %>
To
<% categories.each do |category| %>
Hope this help. :)
Don't use...
<%= categories.each do |category| %>
Use
<% categories.each do |category| %>
When you use <%=, you're outputting the result of the expression. The result of categories.each is categories, the array that is being output. You don't want to output it, so use <% to evaluate the Ruby without outputting the results.

How to create a HTML template in Rails?

I have a long code. For example:
<% Post.limit(10).offset(10).order(id: :desc).each do |post| %>
######## FROM HERE ###########
<% unless post.image.blank? %>
<% img = post.image.split(' ') %>
<% if post.post_type == 1 %>
<div class="post_type1">
<h1>
<a href="post/<%= post.slug %>">
<%= post.title %>
</a>
</h1>
</div>
<% end %>
<% end %>
####### TO HERE #########
<% end %>
So, I want to make this part(FROM HERE <-> TO HERE part) like a template. So I wrote first line, later render or something else, I do not know and the last line for displaying all the page. Can you help me with it?
Just put it in a file (lets call it _post.html.erb) and include it like:
<% Post.limit(10).offset(10).order(id: :desc).each do |post| %>
<%= render partial: 'post', locals: { post: post } %>
<% end %>
Note the use of locals: { post: post } that passes the variable post in your loop to your partial. Another thing to note is that your file name starts with an underscore (_) which is left out when you render the partial.
Read more about partials in Rails guide.

Splitting string into linked words

So I have standart scaffold cycle that prints a string of tags of a meet.
<% #meets.each do |meet| %>
<p class="MeetTags"><%= meet.tags %></p>
<% end %>
How can I separate string of for example 3 words, so that each would be in separate box.
Thank you!
You can do some think like
<% #meets.each do |meet| %>
<% meet_tags = meet.tags.split(' ') %>
<% meet_tags.each do |meet_tag|%>
<p class="MeetTags"><%= meet_tag %></p>
<%end%>
<% end %>
your problem is that meet.tags is an array, so you're telling rails to display the array: that's why you're seeing the square braces.
If you want to split tags into groups of 3, and then show them separated by spaces, you could do this:
<% #meets.each do |meet| %>
<% tag_arr = meet.tags.split(' ') %>
<% tag_arr.in_groups_of_3.each do |tag_subarr|%>
<p class="MeetTags"><%= tag_subarr.reject(&:blank?).join(" ") %></p>
<%end%>
<% end %>
I'm using .reject(&:blank?) because the in_groups_of method will pad the last subarray out with nil, which will mess up your formatting, and maybe cause other problems if you try and do anything with the member elements of tag_subarr.
Assuming that your tags are joined with space:
<% #meets.each do |meet| %>
<% meet.tags.split(' ').each do |word| %>
<p class="MeetTags"><%= word %></p>
<% end %>
<% end %>

Stuck completing my first rails app

I was taking a tutorial online on rails but I got stuck. These are my controller and view files:
/app/controllers/todos_controller.rb:
class TodosController < ApplicationController
def index
#todo_array = [ "Buy Milk", "Buy Soap", "Pay bill", "Draw Money" ]
end
end
/app/views/todos/index.html.erb:
<title>Shared Todo App </title>
<h1>Shared Todo App</h1>
<p>All your todos here</p>
<ul>
<% #todo_array.each do |t| %>
<li> #todo item here </li>
<% end %>
</ul>
I need to change the code #todo item here to show the actual todo item from the array. So I get output as:
Shared Todo App
All your todos here
- Buy Milk
- Buy Soap
- Pay bill
- Draw Money
<title>Shared Todo App </title>
<h1>Shared Todo App</h1>
<p>All your todos here</p>
<ul>
<% #todo_array.each do |t| %>
<li> <% t %> </li>
<% end %>
</ul>
But since you're getting stuck on that part, I suggest you start with a different tutorial or book, something that explains a bit more about what you're doing and why. http://ruby.railstutorial.org/ruby-on-rails-tutorial-book
Instance variables in your controller are passed as instance variables in your view.
Controller:
#todo_array = [ "Buy Milk", "Buy Soap", "Pay bill", "Draw Money" ]
View:
<% #todo_array.each do |t| %>
<li> <%= t %> </li>
<% end %>
Just replace the comment by <%= t %>. Rails will automatically display each value of the array :
<% #todo_array.each do |t| %>
<li><%= t %></li>
<% end %>
As per the tutorial and the little ruby demo it was mentioned that
Accessing each element of array using blocks. arr.each { |a| puts a } prints all the elements of the array.
However you need to just pass <%= t %> in place of comment.
So your final piece of code will be:
<% #todo_array.each do |t| %>
<li> <%= t %> </li>
<% end %>

Resources