how to write each loop for has_many in rails? - ruby-on-rails

employee has many skills
skill belongs_to employee
Skills table have employee_id(foreign key).
I want to display in view

There are 4 ways to get the collections of users.
#employees = Employee.all.joins(:skills)
#employees = Employee.all.includes(:skills)
#employees = Employee.all.eager_load(:skills)
In your view add below code in HTML/HAML/SLIM file.
<% #employees.each do |employee| %>
<tr>
<td><%= employee.name %></td>
<td><%= employee.skills.map(&:title).join(", ") %></td>
</tr>
<% end %>`

You could try with something like this.
In controller return all the employees
so it will be like
#employees = Employee.all.includes(:skills)
and in the view you can do
<% #employees.each do |employee| %>
<tr>
<td><%= employee.name %></td>
<td><%= employee.skills.collect(&:title).join(", ") %></td>
</tr>
<% end %>

Best practice in this case is to write an instance method on your Employee class:
class Employee < ApplicationRecord
has_many :skills
def skills_list
skills.pluck(:title).join(', ')
end
end
And use it like this in your view:
<table>
<tr>
<td><%= #employee.id %></td>
<td><%= #employee.name %></td>
<td><%= #employee.skills_list %></td>
<tr>
</table>

You can use:
<table>
<tr>
<th>Employee </th>
<th>Skills</th>
</tr>
<% #employees.each do |employee|%>
<tr>
<td><%= employee.name %></td>
<td><%= employee.skills.map(&:name).join(', ') %></td>
</tr>
<% end %>
</table>
This above code will list all skill names of each employee.
You can read a complete guide here

Related

How can I fix Blank arrays on Ruby on Rails views?

I am trying to display some information in my views, but it doesn't return any information and it appears completely blank in the view
that's my controller:
class Spree::Admin::StocklogController < Spree::Admin::BaseController
before_action :load_movements
def index
end
def load_movements
#stockmovelog = Spree::StockMovement.all
end
end
And that's my view:
<% #stockmovelog.each do |movement| %>
<tr>
<td><% movement.id %></td>
<td class="align-center"><% movement.quantity %></td>
<td><% movement.created_at %></td>
<td class="align-right"><% movement.updated_at %></td>
<td class="actions"><% movement.action %></td>
</tr>
<% end %>
It will simply create the number of rows from each and keep the content blank, there is something I might be doing wrong?
Just add = to the ERB inside the td's:
<% #stockmovelog.each do |movement| %>
<tr>
<td><%= movement.id %></td>
<td class="align-center"><%= movement.quantity %></td>
<td><%= movement.created_at %></td>
<td class="align-right"><%= movement.updated_at %></td>
<td class="actions"><%= movement.action %></td>
</tr>
<% end %>

render all records in a stored procedure

I am trying to render all the data of a stored procedure in a table in my view but the problem is that the name of the columns can change in each stored query so I can not make the specific field call in the render because each query brings different columns, how could I make the call of the columns name for the (table titles) and render all the data in the unspecified in the name of the data but bring all the results of the query that apparently returns them in an array?
this is my stored_procedures_controller.rb
class StoredProceduresController < ApplicationController
before_action :authenticate_usuario!
def cantidad_productosxpedido
#cantidad_productosxpedido = Stored_procedure.fetch_db_records("exec SPAD_ReporteProductosxPedido '#{Time.now.try(:strftime,"%Y%m%d")}','#{params[:search]}','#{params[:search6]}'")
respond_to do |format|
format.html
format.js
format.xls
end
end
end
this is my model stored_procedure.rb
class Stored_procedure < ActiveRecord::Base
def self.fetch_db_records(proc_name_with_parameters)
connection.select_all(proc_name_with_parameters)
end
def self.insert_update_delete_calculate(proc_name_with_parameters)
connection.execute(proc_name_with_parameters)
end
def self.fetch_val_from_sp(proc_name_with_parameters)
connection.select_value(proc_name_with_parameters)
end
end
I usually do the rendering of the stored this way
<table class="table table-striped table-bordered table-condensed table-hover rwd_auto">
<thead>
<tr>
<th>Ruta</th>
<th>Pedido</th>
<th>IdCliente</th>
<th>Cliente</th>
<th>Nombre Comercial</th>
<th>2010100</th>
<th>2020100</th>
<th>2020200</th>
<th>2020500</th>
<th>2021200</th>
<th>2200500</th>
<th>2200501</th>
<th>2200508</th>
<th>2200509</th>
<th>2201000</th>
<th>2203100</th>
<th>2203101</th>
<th>2203102</th>
<th>2203104</th>
<th>2203108</th>
<th>2203200</th>
</tr>
</thead>
<tbody id="container_productosxpedido">
<%= render partial: "/stored_procedures/cantidad_productoxpedido", collection: #cantidad_productosxpedido %>
</tbody>
</table>
and in the partial _cantidad_productoxpedido
<tr>
<td><%= cantidad_productoxpedido['Ruta'] %></td>
<td><%= cantidad_productoxpedido['Pedido'] %></td>
<td><%= cantidad_productoxpedido['IdCliente'] %></td>
<td><%= cantidad_productoxpedido['Cliente'] %></td>
<td><%= cantidad_productoxpedido['NombreCorto'] %></td>
<td><%= cantidad_productoxpedido['2010100'] %></td>
<td><%= cantidad_productoxpedido['2020100'] %></td>
<td><%= cantidad_productoxpedido['2020200'] %></td>
<td><%= cantidad_productoxpedido['2020500'] %></td>
<td><%= cantidad_productoxpedido['2021200'] %></td>
<td><%= cantidad_productoxpedido['2200500'] %></td>
<td><%= cantidad_productoxpedido['2200501'] %></td>
<td><%= cantidad_productoxpedido['2200508'] %></td>
<td><%= cantidad_productoxpedido['2200509'] %></td>
<td><%= cantidad_productoxpedido['2201000'] %></td>
<td><%= cantidad_productoxpedido['2203100'] %></td>
<td><%= cantidad_productoxpedido['2203101'] %></td>
<td><%= cantidad_productoxpedido['2203102'] %></td>
<td><%= cantidad_productoxpedido['2203104'] %></td>
<td><%= cantidad_productoxpedido['2203108'] %></td>
<td><%= cantidad_productoxpedido['2203200'] %></td>
</tr>
but when changing the name of the columns I do not know how to do to display the data without specifying the names of those columns
UPDATE
I could resolve to display the contents of the table as follows
<%#cantidad_productosxpedido.to_a.each do |foo|%>
<tr>
<%foo.each do |label, value|%>
<td><%= value %></td>
<%end%>
</tr>
<%end%>
but now I try to add the headers of the table
like this:
<%#cantidad_productosxpedido.first.each do |foo|%>
<tr>
<%foo.each do |label, value|%>
<th><%= label %></th>
<%end%>
</tr>
<%end%>
but it does not show correct in the table but renders it as follows
<tr>
<th>title1</th> <td>value1</th>
</tr>
<tr>
<th>title2</th> <th>value2</th>
</tr>
object.attributes.keys will return an array of column names for a given record. You can use that to generate your columns as follows:
<% #cantidad_productosxpedido.each do |cantidad_productoxpedido| %>
<% cantidad_productoxpedido.keys.each do |col| %>
<td><%= cantidad_productoxpedido[col] %></td>
<% end %>
<% end %>
Not tested, but that should work.

show products that belong to orders on admin pannel

I am trying to show the name of each product that belongs to an order on my admin panel but I cant seem to get it.
here are my associations:
OrderItem belongs_to :product
OrderItem belongs_to :order
Product has_many :order_items
Order has_many :order_items
I have tried two different things:
<tbody>
<% #orders.each do |order| %>
<tr>
<td><%= order.id %></td>
<td><%= order.order_items.product.name %></td>
<td><%= order.total %></td>
</tr>
<% end %>
</tbody>
This gets me this error:
undefined method `name' for #<Array:0x0000000535fbb0>
So then I try to loop through like this:
<tbody>
<% #orders.each do |order| %>
<tr>
<td><%= order.id %></td>
<% order.order_items each do |order_item| %>
<% order_item.products each do |product| %>
<td><%= product.name %></td>
<% end %>
<% end %>
<td><%= order.total %></td>
</tr>
<% end %>
</tbody>
And I get this error:
undefined local variable or method `each' for <Class:0x007fce540aa3f0>:0x007fce5417fed8>
Here is my controller code:
def orders
#orders = Order.all
#order_items = OrderItem.all
#products = Product.all
end
I am not sure where I am going wrong any help would be appreciated, thanks.
You can do this in either way you suggest: just keep an eye on your collections vs. items
First Way:
This one puts all your items in a single <td>
<tbody>
<% #orders.each do |order| %>
<tr>
<td><%= order.id %></td>
<td><%= order.order_items.map{ |o| o.product.name }.join(', ') %></td>
<td><%= order.total %></td>
</tr>
<% end %>
</tbody>
Second Way:
Here, each order_item gets its own <td>
<tbody>
<% #orders.each do |order| %>
<tr>
<td><%= order.id %></td>
<% order.order_items each do |order_item| %>
<td><%= order_item.product.name %></td>
<% end %>
<td><%= order.total %></td>
</tr>
<% end %>
</tbody>
You might consider adding some has_many through or delegate relationships in your models in the long term - it will make this kind of association a little tidier.

Rails 5 controller dumping data from database as an array

I'm just starting out in learning Ruby on Rails. I have the following code in movies_controller.
class MoviesController < ApplicationController
def index
#movies = Movie.all
end
end
and my index.html.erb has a table structure to display the data from the database as follows:
<h4><%= pluralize(#movies.size, 'Movie') %> Found</h4>
<table>
<tr>
<th>Movie Title</th>
<th>Rating</th>
<th>Gross Revenue</th>
</tr>
<%= #movies.each do |movie| %>
<tr>
<td><%= movie.title %></td>
<td><%= movie.rating %></td>
<td><%= number_to_currency(movie.total_gross) %></td>
</tr>
<% end %>
</table>
The index.html.erb first dumped the whole movies data as an array and then display the data below it in the table structure shown above. Please what have I got wrong? Thanks.
Remove the = sign from the each block
<% #movies.each do |movie| %>
<tr>
<td><%= movie.title %></td>
<td><%= movie.rating %></td>
<td><%= number_to_currency(movie.total_gross) %></td>
</tr>
<% end %>
You have a extra = when you start the loop. That page should look like
<h4><%= pluralize(#movies.size, 'Movie') %> Found</h4>
<table>
<tr>
<th>Movie Title</th>
<th>Rating</th>
<th>Gross Revenue</th>
</tr>
<% #movies.each do |movie| %>
<tr>
<td><%= movie.title %></td>
<td><%= movie.rating %></td>
<td><%= number_to_currency(movie.total_gross) %></td>
</tr>
<% end %>
</table>

Trying not to repeat myself with Rails data manipulation

I'm fairly new to rails, an an intermediate programmer in general, but I'll try to be as clear as I can.
I have a database table for Products, which owns a field called category. Category has two possible values, call them Category1 and Category 2. The goal is to retrieve all the Products and display them in HTML organized by Category. I can make this work, but I know there has to be a better way.
My method now is to get my Products like so:
#category1_products = Product.all(conditions: { category: "Category1" })
#category2_products = Product.all(conditions: { category: "Category2" })
and then output the data something like this:
<table>
<tr>
<td>Category1 Name</td>
<% #category1_products.each do |product| %>
<td><%= product.name %></td>
<td><%= product.description %></td>
<td><%= product.price %></td>
<% end %>
</tr>
<tr>
<td>Category2 Name</td>
<% #category2_products.each do |product| %>
<td><%= product.name %></td>
<td><%= product.description %></td>
<td><%= product.price %></td>
<% end %>
</tr>
</table>
I would like to accomplish this using a single instance: get all Products at once, group them by Category, and then output them by looping through one Category at a time (including the Category Names). This seems like a pretty elementary concept to me, but I'm having trouble getting my head around it.
#products_by_category = Product.all.group_by(&:category)
This is a Ruby (read: not ActiveRecord) method to turn an Array into a Hash based on some condition of the objects it contains.
In your view (assuming you want one row per product, and not one per category):
<table>
<% #products_by_category.each do |category,products| %>
<tr>
<th><%= category %></th>
</tr>
<% products.each do |product| %>
<tr>
<td><%= product.name %></td>
<td><%= product.description %></td>
<td><%= product.price %></td>
</tr>
<% end %>
<% end %>
</table>
Rails' group_by is great for this type of problem:
#grouped_products = Product.all.group_by(&:category)
and then in the view, just loop over #grouped_products:
<table>
<tr>
<% #grouped_products.each do |category, products| %>
<td><%= category %></td>
<% products.each do |product| %>
<td><%= product.name %></td>
<td><%= product.description %></td>
<td><%= product.price %></td>
<% end %>
<% end %>
</tr>
</table>

Resources