Convert to hash - Ruby on rails - ruby-on-rails

I have this extracted from a table
#<Section id: 12, name: "Seccion 1", created_at: "2018-07-24 15:06:34", updated_at: "2018-07-24 15:06:34", quotation_id: 62, order: 0>
but I want to convert it to hash
name_seccions.each do | section |
section.quotation_id = event_current
#Convert to hash
puts section.inspect
end

section_hash = section.attributes

Related

how to make an array into array of arrays in ruby?

I have a query company_in_outs = company.in_outs.where('date >= ? and date <= ?', Date.today.at_beginning_of_month, Date.today.end_of_month) which is returning me <ActiveRecord::AssociationRelation. now i want to make this array into an array of arrays, those are grouped based on the date value.
for example.
#<ActiveRecord::AssociationRelation [#<InOut id: 2806, date: "2016-06-01", created_at: "2016-06-02 07:01:52", updated_at: "2016-06-16 07:43:45", company_id: 1>,#<InOut id: 2806, date: "2016-06-01", created_at: "2016-06-02 07:01:52", updated_at: "2016-06-16 07:43:45", company_id: 1>,#<InOut id: 2806, date: "2016-06-01", created_at: "2016-06-02 07:01:52", updated_at: "2016-06-16 07:43:45", company_id: 1>,#<InOut id: 2806, date: "2016-06-02", created_at: "2016-06-02 07:01:52", updated_at: "2016-06-16 07:43:45", company_id: 1>,#<InOut id: 2806, date: "2016-06-02", created_at: "2016-06-02 07:01:52", updated_at: "2016-06-16 07:43:45", company_id: 1>,#<InOut id: 2806, check_in: "2016-06-24 16:16:00", check_out: "2016-06-25 01:16:00", date: "2016-06-01", created_at: "2016-06-02 07:01:52", updated_at: "2016-06-16 07:43:45", company_id: 1> ]
from this array i want to make an array of arrays, which needs to be grouped based on the date. meaning all records which contains same date needs to be grouped as one array. like this i want to have an array of arrays.
If you already have all the records loaded:
company_in_outs.each_with_object({}) do |record, hash|
(hash[record.date] ||= []) << record
end.values
if you aren't using Rails (ActiveSupport) you should use inject instead of each_with_object
company_in_outs.inject({}) do |hash, record|
(hash[record.date] ||= []) << record
hash
end.values
I think you should be able to done sorting on db site too.
There is actually a group_by method in Array, but instead of returning array of array, it returns an object with key and array of the same key as value.
In your case:
company_in_outs.group_by do |com|
com.date
end
The code above will return an object grouped by date as a key, and array of the same date as value.
You could loop through the returning object which will return key and value, and do whatever you like :)
Hope this helps!

select all the values of the records belonging to a specific field of the database and save them in a array Active Record

I have the following set of records . I want to save in a array called #texts only
the values of the field text doing an each o a for
1.9.3-p547 :074 > Tweet.all
Tweet Load (0.3ms) SELECT "tweets".* FROM "tweets"
=> [#<Tweet id: 1, text: "hola a todos", zombie_id: 5, created_at: "2014-12-29 23:52:40", updated_at: "2014-12-29 23:52:40">, #<Tweet id: 2, text: "hola como estas", zombie_id: 5, created_at: "2014-12-30 00:09:40", updated_at: "2014-12-30 00:09:40">, #<Tweet id: 3, text: "hello", zombie_id: 5, created_at: "2014-12-30 12:44:41", updated_at: "2014-12-30 12:44:41">]
1.9.3-p547 :075 >
Example
#texts=["hola a todos","hola cmo estas", "hello"];
I would do this:
#texts = Tweet.all.map(&:text)
Or:
#texts = Tweet.pluck(:text)
You should use pluck, as for the documentation:
Use pluck as a shortcut to select one or more attributes without
loading a bunch of records just to grab the attributes you want.
This way you are only select the desired columns and not the "full" record.

Group by part of attribute in hash

I have a model called coverage that looks like this
1.9.3p429 :005 > Coverage.new
=> #<Coverage id: nil, postcode: nil, name: nil, created_at: nil, updated_at: nil>
Here is an example record:
1.9.3p429 :006 > Coverage.find(10)
Coverage Load (7.3ms) SELECT "coverages".* FROM "coverages" WHERE "coverages"."id" = $1 LIMIT 1 [["id", 10]]
=> #<Coverage id: 10, postcode: "N10", name: "N10 - Muswell Hill", created_at: "2013-05-22 14:42:37", updated_at: "2013-05-22 14:42:37">
I've got over 300 postcodes and I want to group them by some values I have in this array
group = ['N','E','EC','LS','TS']
So I would like to do
#postcodes = Coverage.all
run it through something with the above array to get the following hash
#postcode_hash = { 'N' => [ '#Active Record for N1', '#Active Record for N2' ], 'E' => [ '#Active Record for E1', '#Active Record for E2' ] }
# note: not complete should contain all index from the above array
You can use the .group_by{} method:
#postcodes = Coverage.all
#postcodes_hash = #postcodes.group_by{ |c| c.postcode.gsub(/[0-9]/, '') }
Take a look at the group_by documentation:
http://apidock.com/rails/Enumerable/group_by
There is the explicit version of above:
#postcode_hash = {}
group = ['N','E','EC','LS','TS']
group.each{ |code| #postcode_hash[code] = [] }
#postcodes = Coverage.scoped # similar to .all but better
#postcodes.map do |coverage|
code = coverage.postcode.gsub(/[0-9]/, '') # takes off all the numbers of the postcode
#postcode_hash[code] << coverage if #postcode_hash[code]
end

Unexpected behaviour of array.count in ruby

Hi i am using Rails3 when i puts array of subscribers like this
#subscribers = User.all
and puts it.gives me this array
[#<User id: 62, is_activated: true, subscriber: "TEST_DB2", ports_order: 100, created_at: "2012-05-21 14:47:48">, #<User id: 66, is_activated: true, subscriber: "JOHI", ports_order: 100, created_at: "2012-05-22 12:06:19">, #<User id: 68, is_activated: true, subscriber: "ALI-NAQWI", ports_order: 100, created_at: "2012-05-24 11:01:22">]
And when i give command
#subscribers.count #it give me 0 count
Why?????????
Try length instead, it can be a bug in AREL :)
That he is trying to lazy do something. He is giving back proxy object so it can be a problem there. Length will always work on your result value ~ array.

Rails 3: use contents of an array as variables in a where method

I have three models: Isbn, Sale and Channel.
Aim: to get a list in the isbns show.html.erb view which looks something like this:
Isbn: myisbn
Total sales for myisbn: 100
Myisbn sales for channel 1: 50
Myisbn sales for channel 2: 25
Myisbn sales for channel 3: 25
Here are my models.
Isbn.rb model
has_many :sales
has_many :channels, :through => :sales
Sale.rb model (has attributes sales_channel_id, isbn_id, quantity)
has_many :channels
belongs_to :isbn
Channel.rb model:
belongs_to :sale
I've been working in the isbns controller, in the show method, just to get something to work. I thought I'd refactor later - advice on whether any of this stuff should go in the model would be most welcome.
So far I've got this:
#channelisbn = Sale.where("sales_channel_id =?',1).where("isbn_id=?",3)
#channelsalesisbn = 0
#channelisbn.each {|y| #channelsalesisbn =+ y.quantity}
This successfully gets all the sales where Channel ID is 1 and ISBN id is 3. But it's not much use, as the IDs are hard coded. So I got the Channel IDs into an array:
#channellist = Channel.all
#channel = 0
#channelarray = #channellist.map {|z| #channel = z.id}
which gives me a lovely array of [1,2,3,4]
But I can't figure out how to pass the 1, then the 2, then the 3 and then the 4 into a block which can be used to look up an ISBN's sales which have that sales channel id. This is what I tried (still hardcoding the ISBN id - thought I'd tackle one problem at a time), which returned an empty array:
#channelarray.each do |channel|
#channelisbn = []
#channelisbn = Sale.where("sales_channel_id = ?", channel).where("isbn_id = ?",3)
#channelsalesisbn = 0
#result = []
#result << #channelisbn.each {|a| #channelsalesisbn =+ a.quantity}
end
I was then going to sum the contents of the array.
Any help would be gratefully received. This is my first post, so my zero acceptance rate will change soon!
UPDATE
Just to finish this question off, here's where I've ended up, which is great, and ready for tinkering with: an array, nicely grouped, giving me sales by isbn by channel. Thanks for the group_by tip off!
#in the show action in the isbns controller:
#isbn = Isbn.find(params[:id])
#channelarray = Channel.select(:id).all
#channelarray.group_by {|i| Sale.where("channel_id = ?",i).where("isbn_id =?", #isbn)}
From the console, line breaks added for clarity:
(sneakily set #isbn = 3 first of all, since in the console you can't pass params from a view, so the #isbn instance defined in the controller is nil in the console)
ruby-1.9.2-p180 :067 > #channelarray.group_by {|i| Sale.where("channel_id = ?",i).where("isbn_id =?", #isbn)}
=> {[#<Sale id: 1, isbn_id: 3, quantity: 10000, value: 12000, currency: "GBP", total_quantity: nil, created_at: "2011-05-06 12:30:35", updated_at: "2011-05-07 17:43:13", customer: "Waterstone's", retail_price: nil, discount: nil, invoice_date: "2011-05-24">, #<Sale id: 2, isbn_id: 3, quantity: 1000, value: 500, currency: "GBP", total_quantity: nil, created_at: "2011-05-07 09:37:53", updated_at: "2011-05-07 19:14:52", customer: "Borders", retail_price: nil, discount: nil, invoice_date: "2011-02-05">]=>[#<Channel id: 1>],
[#<Sale id: 3, isbn_id: 3, quantity: 500, value: 1500, currency: "", total_quantity: nil, created_at: "2011-05-07 09:38:11", updated_at: "2011-05-07 19:15:07", customer: "Borders", retail_price: nil, discount: nil, invoice_date: "2011-12-05">, #<Sale id: 4, isbn_id: 3, quantity: 45, value: 300, currency: "", total_quantity: nil, created_at: "2011-05-07 09:38:38", updated_at: "2011-05-07 19:15:36", customer: "Borders", retail_price: nil, discount: nil, invoice_date: "2011-06-05">]=>[#<Channel id: 2>],
[]=>[#<Channel id: 3>],
[]=>[#<Channel id: 4>]}
UPDATE 2
Ha, the hash I generated had the key value pairs the wrong way round. The array containing the sales data was the key - it should have been the value. Rubydocs saved the day:
#salesbychannel = #salesbychannelwrong.invert
The invert method switches the key-value pairs. Sweet.
What you're looking for is passing an array to a ARel#where(), like this:
Sale.where(:sales_channel_id => #channelarray)
This should execute an IN query. If that's not working, you can always pass the array to ActiveRecord#find, like this:
Sale.find(#channelarray)
Hope this helps

Resources