What is simplest way to convert :pluck or :collect results to array of strings in Rails? - ruby-on-rails

I have a model called Record and belongs Product model,
the price column type is hexadecimal. Rails already convert it to string in view. But I wanna get them in my console queries.
Example code for pluck:
Product.first.records.pluck(:price)
This query displays the values in array as hexadecimal. There is a method called to_sentences for pluck values but its not enough for my case.
The problem is same in collect method:
Product.first.records.collect(&:price)
What is the pluck query to display my hexadecimal data as array of strings like:
["45,46","75,42"]

Product.first.records.pluck(:price).map(&:to_s)

please try this:
Product.first.records.pluck(:price).join(',')

Related

update columns with update_all & another column but convert values to array

I have column_1(string) and i created column_2(string) and seriallized column_2 as array
class Model < ActiveRecord::Base
serialize :column_2, Array
...
And i need to update column_2 with column_1 values, like this:
Model.update_all('column_2 = column_1')
But because i use serrialize as array for column_2, i need to save all values(strings) from column_1 as array
UPD.
I tried .update_all('column_2 = (array[column_1]), but in this case, anyway when i call column_2 i get it as string:
"{\"value\"}"
Yes, it is possible using below query Use array_to_json to convert to array correctly
Model.update_all("column_2 = (array_to_json(array[column_1]))")
Incorrect: - I am not sure if directly using the SQL to convert the column data would work here. Rails has inbuilt serialize method that converts the data before pushing to sql. So the conversion of string to array is not possible at the sql level. You would need to resort to iterate over the records and update each record like below:-
model_instance.update('column_2 = ?', [column_1])

How do I extract a field from an array of my models in order to form a single query?

I’m using Rails 4.2.7. I have an array of my model objects and currently I’m iterating through that array to find matching entries in the database based on a field my each object …
my_object_times.each_with_index do |my_object_time, index|
found_my_object_time = MyObjectTime.find_by_my_object_id_and_overall_rank(my_object_id, my_object_time.overall_rank)
My question is, how can I rewrite the above to run one query instead of N queries, if N is the size of the array. What I wanted was to force my underlying database (PostGres 9.5) to do a “IF VALUE IN (…)” type of query but I’m not sure how to extract all the attributes from my array and then pass them in appropriately to a query.
I would do something like this:
found_my_object_times = MyObjectTime.where(
object_id: my_object_id,
overall_rank: my_object_times.map(&:overall_rank)
)

ActiveRecord, get only one field (not id) and flatten result array

I have a table and want to get one specific field from every row. When I do select I always get id, which I don't want. After that I want to have the result in a simple array.
This is what I do:
User.all.select(:reg)
This is what I get:
[{"id":null,"reg":"erfa"},{"id":null,"reg":"jhzhegrwe"}]
This is what I want:
{"erfa","jhzhegrwe"}
pluck i believe is what you want, which converts database results in a Ruby array.
This will only return column :reg
User.all.pluck(:reg)

how to get 2-d hash as an output from hstore column?

In rails app I try to store 2-d hash in postgreSql hstore column, but for output I get something like
{"6/5"=>"{\"color\"=>\"white\"}", "8/1"=>"{\"color\"=>\"white\"}", "8/2"=>"{\"color\"=>\"white\"}", "8/3"=>"{\"color\"=>\"white\"}"}.
How can I get 2-d hash as output or maybe you can give some advice for how to parse it?.
If you need to convert this into hash here is how you could it do:
str = {"6/5"=>"{\"color\"=>\"white\"}", "8/1"=>"{\"color\"=>\"white\"}", "8/2"=>"{\"color\"=>\"white\"}", "8/3"=>"{\"color\"=>\"white\"}"}
p str.each_with_object({}){|(k,v),h| h[k] = eval(v)}
Result
{"6/5"=>{"color"=>"white"}, "8/1"=>{"color"=>"white"}, "8/2"=>{"color"=>"white"}, "8/3"=>{"color"=>"white"}}
To store a hash in sql database, you can use a string column and add this line to the model:
serialize :my_hash_thingy
It should handle every serialization / deserialization in the background, and you will have tha hash normally every time you use it.

How to manipulate hash keys to transform numeric months to names

I have an AR query that returns a hash of events per month, ordered by month
o.events.group("to_char(date,'MM')").order("to_char(date,'MM')").size()
I'm using numeric months in this query as it was the best way I could find to get things in the correct order, and I also need to do some other manipulations on the hash.
Before display the results, I need to convert the numeric months back to words. I added the following to the end of the query
.each_key{ |key| Date::MONTHNAMES[key] }
But i get
TypeError: can't convert String into Integer.
So i tried
.each_key{ |key| Date::MONTHNAMES[key.to_i] }
But the months remain in numeric form
{"01"=>4, "02"=>3.....
How can i manipulate this hash to get
{"January"=>4, "February"=>3.....
Make a new Hash. If you can't, make a new key in the current hash and delete the original key. You can't simply change a key, since key is a local variable in the block, and changing it in no way impacts the contents of the Hash.
This ? :
def number_to_month(number)
(Time.now.beginning_of_year + number.months).strftime("%B")
end
There are ways to generate a new hash but I think you could just convert the strings to month names in your view right before displaying them. Use the code you already wrote inside the block in your question but put it in your view.

Resources