i'm having a huge problem with creating this table.
I have a model
Unit
id
floor
unitnumber
here is my current code for view
<% block.units.each do |unit| %>
....
<% end %>
I need to loop through the entire block, get all the unique unitnumber and floor. Create a table like this.
BLOCKNO Unitnumber1 Unitnumber2 Unitnumber3 Unitnumber4 Unitnumber5 Unitnumber6
Floor10 unit_id unit_id unit_id unit_id
Floor9
Floor8
<% block.each do |block| %>
<% block.units.each do |unit| %>
...
<% end %>
<% end %>
Related
How can I get unique values from column in the table?
For example, I have this Products table:
ID NAME CATEGORY
1 name1 1st_cat
2 name2 2nd_cat
3 name3 1st_cat
Here I want to get only 2 values - 1st_cat and 2nd_cat:
<%Products.each do |p|%>
<%=p.category%>
<%end%>
Two more ways:
Product.select(:category).map(&:category).uniq # Ruby does the work
Product.uniq.pluck(:category) # DB does the work (superior)
For Rails >= 5.1 use:
Product.distinct.pluck(:category) # DB does the work (superior)
...because Relation#uniq was deprecated.
I think you can do this:
<% Products.select("DISTINCT(CATEGORY)").each do |p| %>
<%= p.category %>
<% end %>
Source: http://guides.rubyonrails.org/active_record_querying.html#selecting-specific-fields
This does all the work in the database server. The result is a simple array.
<% Product.distinct(:category).pluck(:category).each do |category|
<%= category %>
<% end %>
Rails will generate SQL that works on any database (Postgres, MySQL, etc).
SELECT DISTINCT "products"."category" FROM "products"
I suggest to use Products.all.distinct.pluck(:category) because uniq has been deprecated since rails 5 and it will be removed on rails 5.1
Try this (in the rails console)
Product.group(:category)
Product.group(:category).each { |p| p.name }
For postgres
<% Product.select("DISTINCT ON (category) *").each do |category|
<%= category %>
<%= name %>
<% end %>
Update
even better
<% Product.select(%(DISTINCT ON (category) "#{Product.table_name}".*)).each do |category|
<%= category %>
<%= name %>
<% end %>
because it can return wrong columns when you do joins (e.g. returns id column from joined table, but not products)
If you or anyone want to get two or more attributes from a table like products, based on a distinct feature of an attribute, only this solution will help you for Rails >= 5.1
distinct_products = Product.select("DISTINCT ON (category) *")
# it's an active record relation class.
> distinct_products.class
=> Product::ActiveRecord_Relation
N.B. Don't use .pluck() on the distinct_products. It will reselect from the products table and the distinct feature will not work anymore.
Needed to get unique output and was trying the 'uniq' method unsuccessfully. Tried several solutions posted here unsuccessfully. I'm using devise which gives me access to the current_user method and working with two tables, one being a join (an item has_many :things).
This solution ultimately worked for me :
#current_user.things.select(:item_fk).distinct.each do |thing|
<%= thing.item.attribute %>
<% end %>
How can I add a NULL option to my form select? I have a table:
categories
id
category_id
name
If I'm creating a new category, I want to be able to select the NO_CATEGORY option (NULL value and id).
My view code:
<%= f.collection_select :supercategory_id, Category.all, :id , :name %>
Also, it is a good idea? Isn't it better to have some predefined ROOT category in the database? Thank you.
Try:
<%= f.collection_select :supercategory_id, Category.all, :id , :name, :include_blank => true %>
Its ok to have null. Just have your model logic know that it should create a new category and assign it rather than mass assign from the select. Might be something that happens in a before_validation method
I have did the first one, and want to check if I got it right or not? also I have no idea how to do number 2
Ruby ORM
Consider the following two active record definitions over the tables “customers” and “orders”. The orders table has a foreign key “cust_key” that references the primary key of “customers”, which is also named “cust_key”.
Table:
customers-
cust_key
address
orders-
order key
cust_key
order_priority
total_price
1 class Customer < ActiveRecord::Base
2 set_table_name "customers"
3 set_primary_key "cust_key"
4 has_many :orders, :foreign_key => "cust_key”
5 End
1 class Order < ActiveRecord::Base
2 set_table_name "orders"
3 belongs_to :customer, :foreign_key => "cust_key"
4 set_primary_key "order_key”
5 end
Consider the following piece of Ruby-on-Rails code.
1 <table>
2 <% Customers.all.each.do |c| %>
3 <tr>
4 <td><%= c.address %></td>
5 <td><%= c.orders.count() %></td>
6 </tr>
7 <% end %>
8 </table>
Questions:
Provide the SQL queries that will result from executing this piece of Ruby-on-Rails. How many SQL queries in total will be executed?
2 queries
SELECT address FROM customers
SELECT COUNT(*) FROM orders where orders.cust_key= customers.cust_key;
Write a jsp fragment that issues only one SQL query and creates identical html with the Ruby-on-Rails fragment above.
I know that this is an old question, and you've probably forgotten it but ...
If you change:
<% Customers.all.each.do |c| %>
<tr>
<td><%= c.address %></td>
<td><%= c.orders.count() %></td>
</tr>
<% end %>
to
<% Customers.includes(:orders).each.do |c| %>
<tr>
<td><%= c.address %></td>
<td><%= c.orders.length %></td>
</tr>
<% end %>
You'll display the customer information in one SQL call.
The includes method, changes the request so that it uses a single query with a join, to gather all customers with their corresponding order records
Note that I've used length rather than count, as count will call a SQL count for each customer (c) object, whereas length will look at the length of orders data already gathered in the first SQL call.
I have two models: Product and Categories. They have a HABTM relationship.
At products form i have:
<% Category.find(:all).each do |c| %>
<%= check_box_tag 'product[category_ids][]', c.id, #product.category_ids.include?(c.id) %> <%=c.name%>
<% end %>
It works perfectly but when a categories_products record is created, the created_at field is empty ( 0000-00-00 00:00:00 ).
How can i make Rails create/update those fields?
Thanks.
My table named stocks contains product_id, color_id, storage_id and in_stock as columns.
For a given product I want to group all stocks by storage, then for each storage I want to show product (color): in_stock
How should I write a method and how to render?
<% Stock.all.group_by(&:storage).each do |storage, products| %>
Storage: <%= storage %>
<% products.each do |product| %>
(<%= product.color_id %>): <%= product.in_stock %>
<% end %>
<% end %>
Edit: updated to use ERB, and in_stock as a number and not a boolean yes/no column, and use color_id in place of color.name because that assumes you have a relationship to a color.
Not structured exactly how you need it (not enough info from your post), but something like this perhaps?
items = Stock.select('color_id, in_stock').group('stocks.storage_id').where(:product_id => foo)
items.each {|item| puts "(#{lookup_color(item.color_id)}): #{in_stock}"