I have the following piece of code which print the list of items in separated columns.
- if #product.type_id == 2
%th.order_invoice_cell.each.count
#{l(:item)}
- #product.products.each do |p|
%th.order_invoice_cell
#{l(:item)}
But all the columns are named item, item, item. now if I want to have number mentioned like item1 item2 item3 and so on. how can I do this.
I don't know, what your #{l(:item)} doing. but you can Use this:
- if #product.type_id == 2
%th.order_invoice_cell.each.count
#{l(:item)}
- #product.products.each_with_index do |p, index|
%th.order_invoice_cell
= "item #{index + 1}"
It will give you item 1, item 2 and so on... Thanks
Use each_with_index instead. So you can do #product.products.each_with_index do |p,index|
Related
In my rails app, new line items are created daily. I need to be able to have my smart_listing show how many apples and oranges were ordered. For instance:
Line Item QTY
Apple 2
Orange 1
What I am getting is:
Line Item QTY
Apple 1
Apple 1
Orange 1
line_item_scope = LineItem.all
line_item_scope = line_item_scope.where(created_at: Date.today.beginning_of_day..Date.today.end_of_day)
if customer_signed_in?
line_item_scope = line_item_scope.ticket.customer(current_customer.id)
end
#line_items = smart_listing_create(:line_items, line_item_scope, partial: "line_items/listing2", default_sort: {updated_at: "desc"})
My initial thought was to create a .map(&:name).uniq but that returns an array when I need a relationship to go into the smart listing.
If you need to display just LineItem's name and the number of items of that name, then group method can help:
line_item_scope.group(:name).count
This will construct a hash:
result = { "Apple" => 2, "Orange" => 1 }
Then this hash can be iterated to display the values:
result.each do |name, count|
...
end
Or the number of line items can be selected as a column:
line_items_scope =
LineItem.group(:name)
.order(:name)
.select("name, COUNT(*) as count")
Then line_items_scope can be fed to smart_listing_create as a ActiveRecordRelation
I have a collection/array in rails, transformed to json it looks like this:
#collection = [{"order_number":"123","item":"Paper"},{"order_number":"567","item":"Ruler"},{"order_number":"344","item":"Pen"},{"order_number":"342","item":"Pencil"},{"order_number":"877","item":"Keyboard"}]
I would like to pick the item with the order_number "342" and put it at the last position of the collection, so the new collection looks like this:
#collection = [{"order_number":"123","item":"Paper"},{"order_number":"567","item":"Ruler"},{"order_number":"344","item":"Pen"},{"order_number":"877","item":"Keyboard"},{"order_number":"342","item":"Pencil"}]
In theory, it would look like this:
#collection.last = #collection[3]
but that is obviously not fancy ruby style nor would it re-sort the array as in my example.
Also I don't know the index of the item as it can change depending on what the user shops.
how about:
#collection << #collection.delete_at[#collection.index{|x| x[:order_number] == "342"}]
This basically searches the index of element with :order_number 342 first, uses that index to delete it, and then store the deleted element at the end again.
You can also use the partition method:
#collection = #collection.partition { |h| h['order_number'] != '342' }.flatten
Just split your collection on two (without 342 order and with 342 order), then just join them. It should looks like:
#collection = #collection.select {|e| e[:order_number] != '342' } + #collection.select {|e| e[:order_number] == '342' }
If you have an index of an item it boils down to
#collection << #collection.delete_at(3)
If you don't, you could try finding it using
#collection.find_index{ |el| el["order_number"] == "123" }
Alternative you can try this too:
> #collection.each_with_index{ |key,value| #collection.push(#collection.delete_at(value)) if key[:order_number] == "344" }
#=>[{:order_number=>"123", :item=>"Paper"}, {:order_number=>"567", :item=>"Ruler"}, {:order_number=>"342", :item=>"Pencil"}, {:order_number=>"877", :item=>"Keyboard"}, {:order_number=>"344", :item=>"Pen"}]
In my rails app, I want to add few values present in one column in the form of key-value pair. I am not getting the way to add them.
(byebug) p #timing_params.data_date_wise
{"2"=>"7", "3"=>"8", "4"=>"9", "5"=>"10", "6"=>"11", "9"=>"", "10"=>"", "11"=>""
, "12"=>"", "13"=>"", "16"=>"", "17"=>"", "18"=>"", "19"=>"", "20"=>"", "23"=>""
, "24"=>"", "25"=>"", "26"=>"", "27"=>"", "30"=>"", "31"=>""}
Controller:
total_hour = 0
total_day_count = #timing_params.data_date_wise.count
puts "total_day_count = #{total_day_count}"
for i in 1..total_day_count
total_hour+= #timing_params.data_date_wise["i"] if #timing_params.data_date_wise["i"].to_i > 0
puts "date : #{#timing_params.data_date_wise['i']}"
end
puts "TotalHour : #{total_hour}"
Another problem I think is - All details are not in sequence so that only values will be calculated. For example count is 22 then as per the data - 23 to 31 will be missed.
Please suggest something...
How about changing your for loop to iterate through the hash like this:
#timing_params.data_date_wise.each do |date,value|
total_hour += value.to_i if value.to_i > 0
end
This is an odd problem I'm having. I have a list of names, split up into two arrays at the middle. So names A-M are in name1 and names N-Z are in name2. Now I'm going through each array and putting them in a row with two columns so the names look like this:
Aaron Neil
Arthur Nick
etc. But when I collapse the page down, it looks like:
Aaron
Neil
Arthur
Nick
and I want it to look like:
Aaron
Arthur
Neil
Nick
Here's the haml:
- a = true
- index = 0
- while(a)
- first = name1[index]
- second = name2[index]
- if first != nil || second != nil
.row
.col-md-6
- if first
= first
.col-md-6
- if second
= second
- index += 1
- else
- a = false
I understand why this is happening, but I'm not exactly sure how else to approach this. Does anyone have any insight?
You are creating a new row and column for each set of names.
instead you should run your loop inside the columns like this:
- name1 = %w[Aaron Arthur]
- name2 = %w[Neil Nick]
.row
.col-md-6
-name1.each do |x|
%p= x
.col-md-6
-name2.each do |x|
%p= x
I would like to analyse data in my database to find out how many times certain words appear.
Ideally I would like a list of the top 20 words used in a particular column.
What would be the easiest way of going about this.
Create an autovivified hash and then loop through the rows populating the hash and incrementing the value each time you get the same key (word). Then sort the hash by value.
A word counter...
I wasn't sure if you were asking how to get rails to work on this or how to count words, but I went ahead and did a column-oriented ruby wordcounter anyway.
(BTW, at first I did try the autovivified hash, what a cool trick.)
# col: a column name or number
# strings: a String, Array of Strings, Array of Array of Strings, etc.
def count(col, *strings)
(#h ||= {})[col = col.to_s] ||= {}
[*strings].flatten.each { |s|
s.split.each { |s|
#h[col][s] ||= 0
#h[col][s] += 1
}
}
end
def formatOneCol a
limit = 2
a.sort { |e1,e2| e2[1]<=>e1[1] }.each { |results|
printf("%9d %s\n", results[1], results[0])
return unless (limit -= 1) > 0
}
end
def formatAllCols
#h.sort.each { |a|
printf("\n%9s\n", "Col " + a[0])
formatOneCol a[1]
}
end
count(1,"how now")
count(1,["how", "now", "brown"])
count(1,[["how", "now"], ["brown", "cow"]])
count(2,["you see", "see you",["how", "now"], ["brown", "cow"]])
count(2,["see", ["see", ["see"]]])
count("A_Name Instead","how now alpha alpha alpha")
formatAllCols
$ ruby count.rb
Col 1
3 how
3 now
Col 2
5 see
2 you
Col A_Name Instead
3 alpha
1 how
$
digitalross answer looks too verbose to me, also, as you tag ruby-on-rails and said you use DB.. i'm assuming you need an activerecord model so i'm giving you a full solution
in your model:
def self.top_strs(column_symbol, top_num)
h = Hash.new(0)
find(:all, :select => column_symbol).each do |obj|
obj.send(column_symbol).split.each do |word|
h[word] += 1
end
end
h.map.sort_by(&:second).reverse[0..top_num]
end
for example, model Comment, column body:
Comment.top_strs(:body, 20)